I have this directive, which basically attaches a file to a model through file-model="..."
(the entire purpose of this directive is because ng-model
doesn't work in <input type="file">
in angularjs)
angular.module('myApp').directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
console.log(scope); // DEBUG
var model = $parse(attrs.fileModel);
element.bind('change', function() {
scope.$apply(function() {
model.assign(scope, element[0].files[0]);
});
if (attrs.ngChange) {
scope.$apply(attrs.ngChange);
}
});
}
};
}]);
And I also have a bootstrap-ui modal, modal.html:
<div class="modal-body">
<div class="form-group">
<input type="file" file-model="excelFile" ng-model="dummy" ng-change="uploadFile()" />
</div>
</div>
With its corresponding bootstrap-ui controller:
angular.module('myApp').controller('modalController', ['$scope', '$modalInstance', '$scope', function ($scope, $modalInstance, $scope) {
$scope.uploadFile = function() {
console.log($scope); // DEBUG
var formData = new FormData();
formData.append('file', $scope.excelFile); // empty!
...
};
}]);
I invoke the modal from another controller like this:
$scope.openModal = function () {
var modalScope = $scope.$new();
modalScope.somePassedData = "I pass data this way";
var modalInstance = $modal.open({
templateUrl: 'views/modal.html',
controller: 'modalController',
scope: modalScope,
});
...
};
So... if you notice the three comments:
- First comment
// DEBUG
- Second comment
// DEBUG
- Comment
// empty!
It seems that the scope used by the directive is not the same as the scope where the <input type="file">
is living, and because of this I'm getting an empty file.
What am I doing wrong with scopes?
Also I should mention that this worked fine without using bootstrap ui-modal... so it must have something to do with the scope of the modal