【问题标题】:How to track behavior of ngModel array item using .directive如何使用 .directive 跟踪 ngModel 数组项的行为
【发布时间】:2015-03-03 18:42:29
【问题描述】:

大家好,我在不久前使用 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 我写的下一个角度代码:

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-model,我不知道如何访问像ngModel [1]这样的模型,所以我希望有人能帮助我,谢谢

【问题讨论】:

  • 这很奇怪。您可能希望其他东西知道所有输入并决定添加新输入,而不是将此指令放在每个输入上。如果我们知道您想做什么,也许我们可以提供更好的设计。
  • 如果所有先前的输入都已填写,我只想添加新输入(默认情况下,页面上已经放置了 5 个输入,但如果所有这些都被使用,则自动添加新输入并且新输入已填充添加一个输入等)

标签: javascript angularjs directive watch angular-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();
           }
       }
   );
}
}}]);

【讨论】:

  • 酷!!!,这正是我搜索的,有趣的想法,谢谢你的帮助:)
猜你喜欢
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-26
  • 2019-12-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多