I am attempting to follow this [tutorial] but can't get it working.
My Angular controller is logging undefined
for a model created in my directive.
Here is a [JSFiddle] of it working created my author of tutorial.
The problem is the view can find $scope.myFile
and but controller does not ($scope.myFile
is undefined
).
The view displays {{ myFile.name }}
(as just example my-image.jpg
). The myFile
variable is a JS object containing data on selected file. This works fine. The directive seems to be assigning the model the value of selected file (and thus displays it correctly in view).
<input file-model="myFile" type="file"/ >
<div class="label label-info">
{{ myFile.name }}
</div>
<button ng-click="uploadDocs()">Click</button>
Here is the directive I got from this [tutorial].
Since input type file
can't use ng-model
, this directive sets up the model to be associated with an file
input, assigning to it every time the file fires change
event.
directive('fileModel', [
'$parse',
function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
if (element[0].files.length > 1) {
modelSetter(scope, element[0].files);
}
else {
modelSetter(scope, element[0].files[0]);
}
});
});
}
};
}
]).
In the controller I just log $scope.myFile
. This is called from the button in the HTML above.
Ideally, I'd be uploading the files to server here, but I can't because $scope.myFile
is undefined.
$scope.uploadDocs = function() {
var file = $scope.myFile;
console.log($scope.myFile);
};
Can someone tell me why the view would be recieving $scope.myFile
but the controller logs undefined
for $scope.myFile
?
$scope.myFile = {};
it is mostly the dot problem – entre Nov 24 '14 at 6:02uploadDocs()
function like thisuploadDocs(myfile)
, seemed to do it – Akinwale Aug 21 at 15:29