【问题标题】:Directive error $rootScope:infdig Infinite $digest Loop指令错误 $rootScope:infdig 无限 $digest 循环
【发布时间】:2016-07-13 22:13:14
【问题描述】:

我下载了一个只接收数字并有一些附加选项的指令;但是,在运行它之后,我在以下选项之一中遇到了 rootScope 错误:

<input type="text"  ng-model="mynumber" nks-only-number allow-decimal="false" />

我相信错误的条件会导致此错误出现,但我不知道为什么。

这里是演示: http://jsfiddle.net/RmDuw/896/

代码:

(function(){
    angular.module('myApp', [])
      .directive('nksOnlyNumber', function () {
        return {
          restrict: 'EA',
            require: 'ngModel',
            link: function (scope, element, attrs, ngModel) {   
               scope.$watch(attrs.ngModel, function(newValue, oldValue) {
                  var spiltArray = String(newValue).split("");

                  if(attrs.allowNegative == "false") {
                    if(spiltArray[0] == '-') {
                      newValue = newValue.replace("-", "");
                      ngModel.$setViewValue(newValue);
                      ngModel.$render();
                    }
                  }

                  if(attrs.allowDecimal == "false") {
                      newValue = parseInt(newValue);
                      ngModel.$setViewValue(newValue);
                      ngModel.$render();
                  }

                  if(attrs.allowDecimal != "false") {
                    if(attrs.decimalUpto) {
                       var n = String(newValue).split(".");
                       if(n[1]) {
                          var n2 = n[1].slice(0, attrs.decimalUpto);
                          newValue = [n[0], n2].join(".");
                          ngModel.$setViewValue(newValue);
                          ngModel.$render();
                       }
                    }
                  }


                  if (spiltArray.length === 0) return;
                  if (spiltArray.length === 1 && (spiltArray[0] == '-' || spiltArray[0] === '.' )) return;
                  if (spiltArray.length === 2 && newValue === '-.') return;

                    /*Check it is number or not.*/
                    if (isNaN(newValue)) {
                      ngModel.$setViewValue(oldValue || '');
                      ngModel.$render();
                    }
                });
            }
        };
    });
}());

【问题讨论】:

  • 您的 JSFiddle 与您在此处发布的代码不太相似...这是对的吗?
  • 是一样的,我只是贴在这里直接展示代码

标签: javascript angularjs angularjs-directive


【解决方案1】:

我相信问题在于,查看您粘贴的代码(而不是不同的 JSFiddle),ngModel.$render() 被调用了两次。如果我从 attrs.allowDecimal == false 条件或结尾 isNaN(newValue) 条件中删除它,代码运行正常。

由于我不确定您的最终目标是什么,因此我忽略了实际重写您的代码。但是,这解决了infinite $digest loop 错误。

【讨论】:

猜你喜欢
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
  • 2017-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多