Why is my Angular function called in an infinite loop?

In my application, I have a field input, and if the user enters a specific line (basically a line that matches the regular expression), is displayed div.

(simplified) part of HTML:

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="TodoCtrl">
      <input type="text" ng-model="searchText"/>
      <div>Hello</div>
      <div ng-show="isValid(searchText)">World !</div>
  </div>
</div>

and my controller:

function TodoCtrl($scope) {
    var reg = /20\d{2}/g;    
    $scope.isValid = function(str) {
        console.log('Is valid?');
        return reg.test(str);
    }
}

When a user enters a year (thus confirmed by a regular expression), I get the following error:

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: [["isValid(searchText); newVal: true; oldVal: false"],["isValid(searchText); newVal: false; oldVal: true"],["isValid(searchText); newVal: true; oldVal: false"],["isValid(searchText); newVal: false; oldVal: true"],["isValid(searchText); newVal: true; oldVal: false"]]
http://errors.angularjs.org/1.2.1/$rootScope/infdig?p0=10&p1=%5B%5B%22isVal…2isValid(searchText)%3B%20newVal%3A%20true%3B%20oldVal%3A%20false%22%5D%5D
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:78:12
    at Scope.$digest (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:11472:19)
    at Scope.$apply (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:11682:24)
    at HTMLInputElement.listener (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:15653:13)
    at http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:2562:10
    at Array.forEach (native)
    at forEach (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:300:11)
    at HTMLInputElement.eventHandler (http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.js:2561:5) 

Here is the link to JsFiddle: http://jsfiddle.net/U3pVM/6598/

What is wrong with my code and how to improve it?

+4
source share
3 answers

g reg. , , . , "2001.", true, ".". false.

, , .

+7

$watch , , , .

, :

reg.test(str)

str, , , . : , , . , angular, .

$watch:

function TodoCtrl($scope) {
    var reg = /20\d{2}/g;    
    var isValid = function(str) {
        $scope.show = reg.test(str);
    }
    $scope.$watch('searchText',isValid);

}

fiddle

+1

reg .

function TodoCtrl($scope) {  
    $scope.isValid = function(str) {
        var reg = /20\d{2}/g;
        console.log('Is valid?');
        return reg.test(str);
    }
}

Karolis Juodelė, , g . , reg , g.

Angular double-check the function to make sure that it does not change, but indeed in the second call, it returns false, and then true, then false, etc.

0
source

Source: https://habr.com/ru/post/1547122/


All Articles