我无法通过 angular 指令将数据传递给控制器的函数,指令有一个更改事件。我想在其中传递我的动态 ID。在控制器中我有 myArray
$scope.myArray = [1,2,3,4,5];
我有以下html。
<div ng-repeat="data in myArray track by $index">
<input type="file" ng-upload-change="uploadFile($event, $id)" my-id="$index">
<div>
在控制器中:
$scope.uploadFile = function($event, $id){
var files = $event.target.files;
console.log("id:"+$id);
};
在指令中:
app.directive('ngUploadChange', function() {
return{
scope:{
ngUploadChange:"&",
myId:"="
},
link:function($scope, $element, $attrs){
$element.on("change",function(event){
$scope.ngUploadChange({$event: event, $id : $scope.myId});
})
$scope.$on("$destroy",function(){
$element.off();
});
}
}
});
如您所见,当我将 uploadFile 函数传递给 ngUploadChange 指令时,它总是将第一个 id(在本例中为 1)传递给控制器函数。我不是每次都得到更新的 ID。
提前致谢。
当您想通过函数传递参数时,您可以使用"="
代替"&"
attr 绑定,并且在您的 HTML 中,您可以像这样指定:
<input type="file" ng-upload-change="uploadFile" ... />
而且,我改变了您传递 params 对象的方式,因为不需要创建该对象。
现在,如果您看到下面的代码片段,它会id: x
在每个文件上传时正确记录(从 0 开始)。
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
myApp.controller('MyCtrl', function MyCtrl($scope) {
$scope.myArray = [1, 2, 3, 4, 5];
$scope.uploadFile = function($event, $id) {
var files = $event.target.files;
console.log("id: " + $id);
};
});
myApp.directive('ngUploadChange', function() {
return {
scope: {
ngUploadChange: "=",
myId: "="
},
link: function($scope, $element, $attrs) {
$element.on("change", function(event) {
$scope.ngUploadChange(event, $scope.myId);
})
$scope.$on("$destroy", function() {
$element.off();
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<div ng-repeat="data in myArray">
<input type="file" ng-upload-change="uploadFile" my-id="$index">
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句