首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ng内的指令--重复不起作用

问ng内的指令--重复不起作用
EN

Stack Overflow用户
提问于 2014-11-05 22:26:28
回答 1查看 437关注 0票数 0

我在ngRepeat中使用指令时遇到了问题。我无法获取$scope.files的值。在ngrepeat中使用时,它未定义,但如果不使用ngrepeat,则可以正常工作。我想不出来。非常感谢您的帮助。

在ng-repeat中使用时,$scope.files未定义。如果不在内部使用,效果会很好。

代码语言:javascript
复制
<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:

代码语言: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()
            })
        }
    }
}]);

控制器:

代码语言:javascript
复制
$scope.addassignment = function(){
    if(typeof $scope.assignments == 'undefined'){
        $scope.assignments = [];
    }
    $scope.assignments.push({});
}
console.log($scope.files);
EN

回答 1

Stack Overflow用户

发布于 2014-11-05 23:05:49

你没有在主作用域上创建文件变量,当你使用赋值时,它将赋值给新创建的文件(而不是在控制器上),我对你的代码做了一些修改。

代码语言:javascript
复制
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等)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26759580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档