Directive error $rootScope:infdig Infinite $digest

2019-09-13 03:28发布

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条回答
Emotional °昔
2楼-- · 2019-09-13 04:10

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.

查看更多
登录 后发表回答