Directive error $rootScope:infdig Infinite $digest Loop

天涯浪子 提交于 2019-12-13 07:16:53

问题


I downloaded a directive that receives only numbers and has some additional options; but, after running it I get a rootScope error in one of the options that is:

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

I believe the false conditional is making this error appear, but I don't know why.

Here is the demo: http://jsfiddle.net/RmDuw/896/

Code:

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

回答1:


I believe the problem, looking at your pasted code (not the different JSFiddle), is that ngModel.$render() gets called twice. If I delete it from either the attrs.allowDecimal == false conditional or the end isNaN(newValue) conditional, the code runs fine.

Since I'm not sure what your end goal is, I've neglected to actually rewrite your code. But, that solved the infinite $digest loop error.



来源:https://stackoverflow.com/questions/38362583/directive-error-rootscopeinfdig-infinite-digest-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!