[英]AngularJS ng-file-upload not working inside ng-repeat
我有指令“筆記”,它基本上是一個筆記小部件,我可以在任何頁面上添加,只需添加一個名稱和ID,以允許人們添加該項目的注釋。
用戶應該能夠使用ng-file-upload將文件上傳到他們的筆記中,但是我很難獲得由ng-file-upload指令填充的$scope.files
。 我很確定它像往常一樣愚蠢的范圍,但我無法弄明白。
所以,當我選擇一個文件時,為什么$ scope.files沒有填充?
指示:
angular.module('app').directive('notes', [function () {
return {
restrict: 'E',
templateUrl: 'notes.html',
scope: {
itemId: '@',
itemModel: '@'
},
controller: ['$scope', 'Upload', function($scope, Upload) {
$scope.files = [];
$scope.notes = [
{title: 'first title'},
{title: 'second title'}
];
$scope.$watch('files', function (files) {
console.log(files);
$scope.formUpload = false;
if (files != null) {
for (var i = 0; i < files.length; i++) {
$scope.errorMsg = null;
(function (file) {
uploadUsingUpload(file);
})(files[i]);
}
}
});
function uploadUsingUpload(file) {
file.upload = Upload.upload({
url: '/api/v1/notes/upload_attachment',
method: 'POST',
//headers: {
// 'my-header': 'my-header-value'
//},
//fields: {username: $scope.username},
file: file,
fileFormDataName: 'file'
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
file.upload.xhr(function (xhr) {
// xhr.upload.addEventListener('abort', function(){console.log('abort complete')}, false);
});
}
}]
};
}]);
模板:
<ul>
<li ng-repeat="note in notes">
{{note.title}}
<div ngf-select ng-model="files"><b>upload</b></div>
</li>
</ul>
<pre style="border: 1px solid red;">{{files | json}}</pre>
我有點遲到了,但是你在更新$ scope.files屬性時遇到問題的原因是因為你的ng-repeat中正在創建一個新的范圍。
<ul>
<li ng-repeat="note in notes">
{{note.title}}
<div ngf-select ng-model="$parent.files"><b>upload</b></div>
</li>
</ul>
<pre style="border: 1px solid red;">{{files | json}}</pre>
有關角度檢查中作用域如何工作的更多信息,請訪問https://github.com/angular/angular.js/wiki/Understanding-Scopes
ng-file-upload在封閉范圍內的“files”模型(或綁定到ng-model的屬性)中設置所選文件對象。 在這種情況下,封閉范圍是ng-repeat。 如果在note對象中設置屬性“files”並將其設置為ng-model,它應該可以工作。
http://plnkr.co/edit/oVpgrSWQAcFdV26aVKv7?p=preview
<ul>
<li ng-repeat="note in notes" >
{{note.title}}
<div ngf-select ng-model="note.files"><b>upload</b></div>
</li>
</ul>
// In directive
$scope.notes = [{
title: 'first title',
files: []
}, {
title: 'second title',
files: []
}];
//And you can watch the file model
$scope.$watch(function($scope) {
return $scope.notes.
map(function(note) {
return note.files;
});
}, function(files) {
console.log('Files' + files);
}, true)
我用ngf-select添加了動態id,它對我很好。
<ul>
<li ng-repeat="note in notes">
{{note.title}}
<div ngf-select id="file{{$index}}" ng-model="files"><b>upload</b></div>
</li>
</ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.