Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Angular.js calling my function so frequently with ng-change and how do I make it call only once per change?

I'm building my first proper angular.js app after going through many tutorials. I've hit a problem with the ngChange directive. I'm trying to use it to call a function each time the value of a drop down list is changed by the user. I find that it calls the function multiple times upon page load and also multiple times each time the option is selected.

I've put together this jsfiddle which demonstrates the problem I'm having.

I'd like to know why it's exhibiting this behaviour and how I can achieve my desired outcome of one function call per option change and no calling of change() on page load. (this second criterion is less critical for my app, but I would like to know how to suppress this behaviour nonetheless).

I've reproduced the code below for those of you who may be able to 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'm aware this could well be due to my improper use/understanding of the angular methodology. I'd appreciate answers that address all the failings of this small example.

like image 586
Jeshua Avatar asked Dec 05 '25 19:12

Jeshua


1 Answers

Anything inside ng-change is already recognised by angular, so you don't need to wrap it in {{ }}. Just ng-change="change()" will do.

Wrapping it in braces will cause angular to evaluate it on page load and any time it updates the view, hence it firing multiple times.

like image 153
noj Avatar answered Dec 08 '25 08:12

noj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!