I've got a directive which defines a input field of type="file", which I can print and is not empty, namely:
<form class="form-horizontal" role="form">
<input type="file" file-model="myFile"/>
{{myFile}} <-- this prints fine
<button type="submit" class="btn btn-success" ng-click="saveData()">Post</button>
</form>
which I can see if called in the view
app.js
.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(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
What I am trying to do now is access the field inside my controller:
.controller('Ctrl', function($scope, fileUpload) {
...
$scope.myFile; <-- initialise it
$scope.saveData = function() {
var file = $scope.myFile;
console.log(file); <-- prints out as undefined
}
.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
But file is undefined.
Any ideas why that would happen and how to access the value of the field?
$scope.myFileinitialized in your controller? Otherwise it will only available in the view.