Why does Angular.js often call my function with ng-change, and how to make it call only once per change?

I am building my first suitable angular.js application after going through many tutorials. I ran into a problem with the directive ngChange. I try to use it to call a function every time the value of the dropdown list is changed by the user. I find that it calls the function several times when the page loads, as well as several times each time an option is selected.

I put together this jsfiddle which demonstrates the problem I am facing.

I would like to know why this exhibits this behavior and how I can achieve the desired result of one function call for each option change and not call it change()when the page loads. (this second criterion is less critical for my application, but I would like to know how to suppress this behavior nonetheless).

I have reproduced the code below for those of you who may find an immediate error.

HTML

<body ng-app ng-controller="Controller">
<div>
    <h2>Number of changes: {{numOfChanges}}</h2>
    <select ng-change="{{change()}}" ng-model="currentSelection">
    <option ng-repeat="option in options">{{option}}</option>
    </select>
</div>
</body>

Javascript

Controller = function($scope) {
    $scope.numOfChanges = 0;
    $scope.change = function() {
        $scope.numOfChanges++;
    }
    $scope.options = ["do", "ray", "me", "far", "so", "la", "tee","dah"]
}

I know this may be due to misuse / understanding of the angular methodology. I would appreciate answers that relate to all the shortcomings of this small example.

+3
source share
3 answers

, ng-change angular, {{}}. ng-change="change()" .

, angular , .

+5

{{ }} ng-change()

<select ng-change="change()" ng-model="currentSelection">

{} , , .

ngChange

Fiddle

+1

DKM jonnyynnoj , , ng-change.

, 10 , , "" 10 , , : http://docs.angularjs.org/api/ng. $rootScope.Scope # $

$digest() AngularJS. , :

. - , $digest() , . . throw " ". 10.

In the javascript developer console, you can also see that your example causes the following error: Error: 10 $ digest () fighters reached. Aborting!

+1
source

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


All Articles