我有一系列可以重複使用的項目。在ng-repeat內部有一個需要傳遞給它的$索引的指令。 指令中的repeaterIndex始終爲0,即使該數組內有多個項目。我試過傳遞的類別而不是$索引,它總是第一類傳遞給指令。
這裏的控制器代碼
angular.module('app')
.controller('ImageUploadCtrl', ['$scope', 'fooSvc',
function ($scope, fooSvc) {
fooSvc.getCategories().then(function(response){
$scope.categories = response.data;
}, function (error) {
console.log(error);
});
$scope.uploadCategoryPhoto = function(categoryIndex){
//upload photo
};
}]);
NG重複碼:
<li ng-repeat="category in categories">
<my-directive repeater-index="{{$index}}" image-object="category.newFeaturedImageObj" callback="uploadCategoryPhoto"></my-directive>
</li>
myDirective.js
angular.module('app')
.directive('myDirective', [function() {
return {
restrict: 'E',
scope: {
callback: '=',
imageObject: '=',
repeaterIndex: '@'
},
templateUrl: 'app/myDirective/myDirective.html',
link: function(scope) {
scope.handleFileSelect = function(element) {
var file = element.files[0];
var reader = new FileReader();
reader.onload = function (event) {
scope.$apply(function() {
scope.imageObject.image = event.target.result;
scope.callback(scope.repeaterIndex);
});
};
reader.readAsDataURL(file);
};
}
};
}]);
myDirective.html
<div>
<input id="upload" type="file" accept="image/*"
onchange="angular.element(this).scope().handleFileSelect(this)"/>
<label for="upload">
Upload
</label>
</div>
如果我用在另一個地方的指令,並給它一個不同的回調屬性,如回調=「Foobar的」,該指令仍然會打電話uploadCategoryPhoto。就好像頁面上的所有指令都採用第一個指令的屬性。
你可以提供一個蹲跳者嗎?所以我們可以幫助你解決它,很多代碼,很難弄清楚整個流程。 – Mikki
我試圖在jsfiddle中重現它,但我無法完成它。我不確定這種差異會使它表現如何。 –
嘗試比較版本與js小提琴 – Mikki