javascript - ng-repeat 内的指令不起作用

标签 javascript angularjs

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

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

<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()
            })
        }
    }
}]);

Controller :

$scope.addassignment = function(){
    if(typeof $scope.assignments == 'undefined'){
        $scope.assignments = [];
    }
    $scope.assignments.push({});
}
console.log($scope.files);

最佳答案

您不会在主作用域上创建文件变量,当您使用分配时,它将分配给新创建的文件(不在 Controller 上),我对您的代码进行了一些修改,

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

附:您还可以在指令中使用作用域绑定(bind)来代替 $parse。

此外,当你像这样直接分配时,它总是会覆盖文件,因为原型(prototype)继承在 JS 中的工作方式,使用对象/数组而不是在更深的范围内分配值(例如 ng-model/ng-repeat 等)

关于javascript - ng-repeat 内的指令不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26759580/

相关文章:

javascript - 如何在 React Native 中对组件数组进行排序?

javascript - 如何使用 meteor 定期更新变量

javascript - 返回 JsonConvert.SerializeObject(json) [.NET 处理程序] 后在 javascript 上解析 JSON

javascript - 带 Bootstrap 的 Angularjs 下拉菜单

javascript - _.keys 未找到 Firebug 中显示的每个项目

javascript - 在通过 AJAX 传递给 JavaScript 函数的 HTML 字符串中插入 PHP 变量?

javascript - 自定义滚动条(垂直)内的自定义滚动条(水平)

javascript - 如何在最后加载$scope.$?

javascript - 将 id 传递到 url 以获取 angular.js 中的单个 View

angularjs - Django 后端带有动态前端(Angularjs)?