当我试图在ngRepeat中调用指令失败时。 但是如果在ngRepeat之外调用相同的指令工作正常。
请检查以下代码:
<html>
<head>
<script src ="//ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<div ng-repeat="list in lists">
<div>{{fileName}}</div>
<input type = "file" id=list file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'E',
link: function($scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
$scope.$apply(function(){
modelSetter($scope, element[0].files[0]);
});
});
}
};
}]);
myApp.controller('myCtrl', ['$scope', function($scope){
$scope.lists=[1,2,3];
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
$scope.fileName=file.name;
/* var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);*/
};
}]);
</script>
</body>
</html>
如何从ng-repeat调用指令?
答案 0 :(得分:0)
您将指令限制为&#39; E&#39; - 元素并将其用作属性。将限制属性更改为EA。
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'EA',
link: function($scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
$scope.$apply(function(){
modelSetter($scope, element[0].files[0]);
});
});
}
};
}]);