[英]How to access $files from child scope with AngularJs
我有一個指令,我可以像這樣使用:
<input type="file" ng-file-select="onFileSelect($files)" multiple>
這在主范圍內工作正常,但是當我嘗試在轉發器中使用它然后在內部包括:
<div ng-repeat="tab in tabs">
<div ng-include="tab.url"></div>
</div>
tab.url:
<input type="file" ng-file-select="onFileSelect($files)" multiple>
它停止工作,沒有數據發送到范圍。
ngFileSelect指令:
app.directive("ngFileSelect", function () {
return {
link: function ($scope, el) {
el.bind("change", function (e) {
for (var i = 0; i < e.target.files.length; i++) {
$scope.file = (e.srcElement || e.target).files[i];
$scope.getFile();
}
});
}
};
});
在我的控制器中我有:
$scope.getFile = function() {
fileReader.readAsDataUrl($scope.file, $scope)
.then(function(result) {
$scope.images.push(result);
});
};
如何在選項卡中訪問所包含文件中選擇的文件?
嘗試:
$scope.getFile = function() {
var currentScope = this; //access the file from current scope instead of from $scope which is always your controller's scope
fileReader.readAsDataUrl(currentScope.file, currentScope)
.then(function(result) {
currentScope.images.push(result);
});
};
原因是范圍繼承, ng-repeat
和ng-include
創建子范圍。 所選文件將分配給子范圍 :
$scope.file = (e.srcElement || e.target).files[i];
然后打電話:
$scope.getFile(); //this is inherited from parent scope (controller)
在getFile
函數中,您正在訪問沒有分配file
$scope.file
(您的控制器范圍)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.