指令错误$ rootScope:infdig无限$ digest循环 [英] Directive error $rootScope:infdig Infinite $digest Loop
问题描述
我下载了一条指令,该指令仅接收数字并具有一些其他选项;但是,运行它之后,在以下选项之一中出现了rootScope错误:
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.
这是演示: 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),是ngModel.$render()
被调用了两次.如果我将其从attrs.allowDecimal == false
条件或结尾isNaN(newValue)
条件中删除,则代码可以正常运行.
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.
由于我不确定您的最终目标是什么,因此我忽略了实际重写您的代码的方法.但是,这解决了无限的$digest
循环错误.
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.
这篇关于指令错误$ rootScope:infdig无限$ digest循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!