如何使用 .directive 跟踪 ngModel 数组项的行为

How to track behavior of ngModel array item using .directive

大家好我不久前才使用 angularjs,现在我有一个与此框架相关的问题我无法解决。所以接下来的问题是:我有几个通过 ng-repeat 生成的输入字段:

<div class="form-group" ng-repeat="(i, name) in name_list track by $index">
<div class="row">
    <div class="col-xs-12">
        <input class="form-control" type="text" ng-model="data.name_list[i]" add-input/>
    </div>
</div>

其中 name_list 一些包含数据的数组。结果我生成了输入字段。接下来我想做的是添加新的输入字段,如果所有以前的字段都是 $dirty 我接下来写的东西 angular 代码:

userApp.directive('addInput', ['$compile', '$sce', function ($compile, $sce) {
return {
    restrict: 'A',
    require: '?ngModel',

    link: function (scope, element, attrs, ngModel) {

       scope.inputCounter = scope.name_list.length;

       scope.$watch(
           function(){
                 return ngModel.$dirty
           },

           function(dirty_val){
               if (dirty_val){

               scope.name_list.push(ngModel.$modelValue);
               }
           }
       );
    }
}}]);

但是这段代码当然会出错(如果最后一个字段是 $dirty,它会添加新字段)我知道为什么会出错,但我不知道如何单独跟踪所有 ng-models,我不知道知道如何访问像 ngModel[1] 这样的模型,所以我希望有人能帮助我,谢谢

您可以添加一个父指令,它将收集脏元素,并在检测到所有其他元素都是脏元素后添加新元素:

检查this plunker

HTML:

<div collect-input>
    <div class="form-group" ng-repeat="(i, name) in name_list track by $index">
    <div class="row">
        <div class="col-xs-12">
            <input class="form-control" type="text" ng-model="data.name_list[i]" add-input/>
        </div>
    </div>
</div>

一旦 addInput 检测到它是脏的,调用父指令控制器:

if (dirty)
    collectInput.reportInput();

JS:

directive('collectInput', function() {
  return {
  restrict: 'A',
  controller: function($scope) {
    var dirtyCount = 0;
    this.reportInput = function() {
      var count = $scope.name_list.length;
      dirtyCount++;
      if (count === dirtyCount) {
        $scope.name_list.push('aaa');
      }
    }
  },
  }
}).
directive('addInput', ['$compile', '$sce', function ($compile, $sce) {
return {
    restrict: 'A',
    require: ['^collectInput', '?ngModel'],

    link: function (scope, element, attrs, ctrls) {
       var collectInput = ctrls[0]
       var ngModel = ctrls[1];
       scope.inputCounter = scope.name_list.length;

       scope.$watch(
           function(){


     return ngModel.$dirty
       },

       function(dirty_val){
           if (dirty_val){
             collectInput.reportInput();
           }
       }
   );
}
}}]);