2

For a setup like this:

HTML

<li ng-repeat="item in data.checkList">                
   <i ng-class="faClass(item.status)">&nbsp;</i>&nbsp;<span>{{item.Name}}</span>
</li>

JS

$scope.data.checkList = [
   {'status':'COMPLETED', 'name':'Task 1'},
   {'status':'NOT STARTED', 'name':'Task 2'}
];

$scope.faClass = function(status){
   console.log(status);
};

BROWSER CONSOLE

COMPLETED
NOT STARTED
COMPLETED
NOT STARTED

Is this behavior expected? How do I solve it and avoid the duplication?

JSFIDDLE

Demo

asprin
  • 9,579
  • 12
  • 66
  • 119

2 Answers2

0

Yes It's normal, basically AngularJS uses dirty-checking to figure out what (and when) to repaint.

How does data binding work in AngularJS?

var app = angular.module('myApp', []);
app.controller('AppCtrl', function($scope) {
$scope.data ={};
 $scope.data.checkList = [
   {'status':'COMPLETED', 'name':'Task 1'},
   {'status':'NOT STARTED', 'name':'Task 2'}
];

$scope.faClass = function(status){
   console.log(status);
};
});
<!DOCTYPE html>
<html>
<head> 
</head>

<body>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
 <div ng-app="myApp" ng-controller="AppCtrl">
  <div class="form-group">
  <li ng-repeat="item in data.checkList">                
   <i ng-class="faClass(item.status)">&nbsp;</i>&nbsp;<span>{{item.name}}</span>
</li>
</div>
 </div>
</body>

</html>
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
0

This is expected behavior of AngularJS. AngularJS uses a digest cycle to check if there any changes to variables. Therefore, as part of the digest cycle's dirty checking, it will check a few times to ensure there have been no changes to the variable. See more in the 'Scope Life Cycle' section: $scope.

If you want the value to only be bound once you can prepend :: to your function call. Note: It's still going to be called twice, but it will be called no more than twice using ::.

<i ng-class="::faClass(item.status)">&nbsp;</i>&nbsp;<span>{{item.Name}}</span>
Ben
  • 2,441
  • 1
  • 12
  • 16