我有這條指令,它基本上通過file-model="..."
將文件附加到模型中(此指令的全部目的是因爲ng-model
在<input type="file">
中不起作用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);
}
});
}
};
}]);
而且我也有一個引導的UI模式,modal.html:
<div class="modal-body">
<div class="form-group">
<input type="file" file-model="excelFile" ng-model="dummy" ng-change="uploadFile()" />
</div>
</div>
與其對應的引導,UI CONTRO米勒:
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!
...
};
}]);
我調用模式從另一個控制器是這樣的:
$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,
});
...
};
所以...如果你注意到了三點意見:
- 首評
// DEBUG
- 二評論
// DEBUG
- 評論
// empty!
看來,由指令使用的範圍是不一樣的,其中<input type="file">
是生活的範圍,也正因爲如此,我得到一個空文件。
我在做什麼樣的範圍錯誤?
而且我應該指出,這個工作得很好,而無需使用引導界面模態...所以它必須有一些與模態
答案在這裏:'var modalScope = $ scope。$ new();'。 '$ scope。$ new()'創建一個從'$ scope'繼承的新的子範圍。因此'$ scope'中的任何內容都應該在'modalScope'中。但是你說你「從另一個控制器調用模態」。控制器具有獨立的作用域,所以'$ scope.excelFile'很可能位於另一個作用域而不是'modalScope',對吧? – 2014-10-07 14:32:05
你已經看到[這個相關的SO帖子](http://stackoverflow.com/questions/18716113/scope-issue-in-angularjs-using-angularui-bootstrap-modal?rq=1)正確,你試圖初始化'$ scope.input = {}'並且它不起作用? – Michael 2014-10-07 14:32:19
對不起,我沒有關注你......但我曾嘗試初始化$ scope.excelFile在模態 – sports 2014-10-07 14:40:59