我在ngRepeat中使用指令时遇到了问题。我无法获取$scope.files的值。在ngrepeat中使用时,它未定义,但如果不使用ngrepeat,则可以正常工作。我想不出来。非常感谢您的帮助。
在ng-repeat中使用时,$scope.files未定义。如果不在内部使用,效果会很好。
<button class="btn btn-success login-button" ng-click="addassignment()">+</button>
<table>
<tr ng-repeat = "assignment in assignments">
<td><input class = "filegap" type = "file" file-model="form.cv" ng-model="form.cv" ng-file-select="fileselected(newemp.email)" file-input="files" multiple/></td>
</tr>
</table>javascript:
app.directive('fileInput', ['$parse', function($parse, $compile){
return {
restrict:'A',
link:function(scope,elm,attrs){
elm.bind('change', function(){
$parse(attrs.fileInput)
.assign(scope,elm[0].files)
scope.$apply()
})
}
}
}]);控制器:
$scope.addassignment = function(){
if(typeof $scope.assignments == 'undefined'){
$scope.assignments = [];
}
$scope.assignments.push({});
}
console.log($scope.files);发布于 2014-11-05 23:05:49
你没有在主作用域上创建文件变量,当你使用赋值时,它将赋值给新创建的文件(而不是在控制器上),我对你的代码做了一些修改。
angular.module('myApp',[]).controller('Main', ['$scope', function($scope) {
$scope.files = [];
$scope.addAssignment = function(){
if(typeof $scope.assignments == 'undefined'){
$scope.assignments = [];
}
console.log('add');
$scope.assignments.push({});
}
console.log($scope.files);
$scope.$watch('files.length', function() {
console.log($scope.files);
});
}]).directive('fileInput', [function() {
return {
restrict:'A',
link:function(scope,elm,attrs){
var files = scope[attrs['fileInput']];
elm.bind('change', function(){
files.push(this.files);
scope.$apply()
});
}
}
}]);你可以在这里看一下:http://plnkr.co/edit/mhXKdlDG5lg8Xnw50lua?p=preview
附注:您还可以在指令中使用作用域绑定,而不是该$parse。
此外,当你直接像那样赋值时,它将总是覆盖文件,因为原型继承在JS中是如何工作的,使用对象/数组来在更深的作用域中赋值(比如ng-model / ng-repeat等)
https://stackoverflow.com/questions/26759580
复制相似问题