Despite browsing through various resources on this topic, I have not found a satisfactory answer to my question. The problem lies in a function that retrieves data from my database - when I execute it using ngInit
, the function runs three times, whereas on an ngClick
event, it only runs once, which is the desired behavior.
I came across some discussions mentioning that the repetition of the function is due to Angular watchers keeping track of code changes. While the repeated execution does not bother me much, the real issue arises when I set a variable to true
at the beginning of the function and then switch it to false
upon getting the data. Unfortunately, the variable goes back to being false prematurely, causing the code to run again unnecessarily.
For example:
controller.getItem = function(){
controller.loading = true;
service.getSelectedItem($routeParams._id).then(function(response){
if(response.data.state === 'success'){
controller.myItem = response.data.item;
controller.loading = false;
}
});
}
HTML:
<div id="item">
<button id="clickMe" ng-click="controller.getItem()">Get data</button>
<div class="panel panel-new">
<div class="panel-header">
<div class="row">
<div class="col-xs-12">
<h4>My Item - {{ controller.myItem._id }}
<small>added on: {{ controller.myItem.dateAdded | date: 'dd MMM yyyy' }}</small></h4>
</div>
</div>
</div>
</div>
</div>
After running thrice, my loading screen disappears but the content remains undefined. It is only after the third iteration that the content actually gets populated.
In summary, while the function works perfectly with an ngClick
, executing it with ngInit
causes it to run three times, disrupting its intended functionality. I am uncertain about how to tackle this issue effectively.