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.
<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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With