I am trying to execute this [tutorial] but cannot make it work.
My Angular controller registers undefined for the model created in my directive. Here is the [JSFiddle] from which he created my tutorial author.
The problem is that the view can find $scope.myFile , but the controller is not ( $scope.myFile is undefined ).
The view displays {{ myFile.name }} (as an example, my-image.jpg ). The variable myFile is a JS object containing the data in the selected file. It works great. This directive seems to assign the model the value of the selected file (and thus render it correctly).
<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 the input type file cannot use ng-model , this directive sets the model that should be associated with the input file , assigning it every time the file fires a 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 simply register $scope.myFile . This is invoked using the button in the HTML above. Ideally, I would upload the files to the server here, but I cannot, because $scope.myFile is undefined.
$scope.uploadDocs = function() { var file = $scope.myFile; console.log($scope.myFile); };
Can someone tell me why the view will receive $scope.myFile , but the controller will register undefined for $scope.myFile ?