سؤال

I am in the early stages of learning AngularJS and am seeing a strange behavior. When my page loads, the associated controller is called 10 times. I have a fiddle here that reveals behavior. As you enter a char in the input box, you will see it is called another 11 times.

    <html>
<head>
<script
    src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.js"></script>
    <script type="text/javascript">
        var HelloCtrl = function($scope) {
            var keysTyped = 0;
            $scope.name = 'World';

            $scope.i = function() {
                return keysTyped++;
            };
        }
</script>Angular controller being called 10 times on init
</head>
<body ng-app>
    <div ng-controller="HelloCtrl">
        Say hello to: <input type="text" ng-model="name"/><br/>
        <h1>Characters typed, {{i()}}!</h1>
    </div>
</body>
</html>
هل كانت مفيدة؟

المحلول 2

The problem you have in your code is called infinite digest loop. When you click the button you are not just returning a value you are updating it at the same time which triggers another digest cycle which triggers another one and so on. This can happen up to 10 times and after it throws an error. If you check the console on that fiddle you added you ll see the error on the console.

Have a look at angularjs' documentation.

نصائح أخرى

First of all, you see it being called exactly 10 times because that's the limit ammount of $digest cycles that can be run before angular throws an exception.

That usually happens when you change object properties during the render process. This would trigger a new render and therefore a loop wich will cause the "10 $digest() iterations reached. Aborting!" error. (a.k.a Infinite $digest loop)

You can solve this changing your code to this:

    <div ng-controller="HelloCtrl">
            Say hello to: <input type="text" ng-model="name" ng-change="i()"/><br/>
    <h1>Characters typed, {{keysTyped}}!</h1>
</div>

and on your controller:

     $scope.keysTyped = 0;

     $scope.i = function () {
        $scope.keysTyped++;
     };

What I've done was simply making use of Angular's two-way binding to solve the problem.

I've took your code and modified it just to make it work and explain why you're getting an Infinite $digest loop.

If all you want is to have a count of characters in the input field, all you need to do is this:

    <body ng-app="">
        <div ng-controller="HelloCtrl">
            Say hello to: <input type="text" ng-model="name"/><br/>
    <h1>Characters typed, {{name.length || 0}}!</h1>
        </div>
    </body>

You don't need a function to count the characters.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top