I have code on https://jsfiddle.net/8t45enfg/2/
The source code is quite simple, suppose the array list have only one element
HTML code:
<div ng-controller="myController">
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Job</th>
</tr>
<tr ng-repeat="a in list" ng-click='doClick()'>
<td ng-if='doCheck()'>{{ a.name }}</td>
<td>{{ a.age }}</td>
<td>{{ a.job }}</td>
</tr>
</table>
</div>
Js code
module.controller("myController", function($scope) {
$scope.list = [ { name: 'test', age: 100, job: 'IT'} ]
$scope.doClick = function() {
console.log('doClick');
}
$scope.doCheck = function() {
console.log('doCheck');
return true;
}
});
- When I run my code, doCheck() is executed twice, why? It should be executed once
- The main question is when I click on data row, both doCheck and doClick are called, I thought it would call just doClick, not doCheck, because I had no action on doCheck. This made me difficult to understand
I'm not a complete expert on the topic but here is my understanding of your problem.
Whenever a change is made on your page, the page is set to "dirty" and when the next cycle hits the
ng-if
, it will be re-evaluated.So to answer your first question, the
ng-if
is evaluated when it is loaded (callingdoCheck()
), then the rest of the page is loaded, causing the page to be set to "dirty", so theng-if
is re-evaluated, causingdoCheck()
to be called again.This causes "doCheck" to appear twice.
This is the same for your second question. Whenever you click, the
doCheck()
is re-evaluated, causing bothdoClick()
anddoCheck()
to be called. If you want to avoiddoCheck()
being called each time, use a variable in yourng-if
, then create a function to change that variable.I hope that helps, I'm sure some angular wizard will be able to give you a better answer!