I am facing a problem in ng-class.
When i click on the the button, click function gets called may times(number of element in ng-repleat). JsFiddle link
var myModule = angular.module('app', []); myModule.controller('myCtrl', function($scope) { $scope.num = [1, 2]; $scope.getClass = function(a) { console.log("class set"); return true; }; $scope.clicked = function() { console.log("clicked"); }; });
.red { color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="app"> <div ng-controller="myCtrl"> <button ng-repeat="n in num" ng-class="{'red':getClass('red')}" ng-click="clicked()">{{n}}</button> </div> </div>
Nothing unusual here. When you click, you potentially triggers a change in the model and therefore angular triggers a digest cycle.
As the getClass
function is bound to an ng-class
directive, the function is evaluated during the digest.
Note: you could avoid the ng-class
being recalculated by using one-time binding, which is an angular 1.3+ feature:
ng-class="::{'red':getClass('red')}"
See fiddle
The functions in partials are called with each $digest
cycle and each triggered $digest
runs twice
I've updated your fiddle with a dummy function that triggers $digest
http://jsfiddle.net/mgPGS/516/
$scope.testDigest = function(){
$timeout(angular.noop)
}
if you click on digest button every function will be triggered twice, if you use angular 1.3+ you can use ::
for one time binding
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.