Reputation: 3137
I have a simple tabs UI made with angularJs bootstrap directive.
I need to count how many div are on the page with some id. The problem is that angular evaluate the function at each tab click. Is this normal? How can I make a function be called only first time?
PLUNKR: http://plnkr.co/edit/HIRzYOVX8huEDL2snqJM?p=preview
$scope.test = function(){
$scope.myId = window.document.getElementById("ciccio")
}
Upvotes: 1
Views: 259
Reputation: 8834
The problem with your first attempt was that the function was placed inside angular's view data binding {{}} so it was called whenever something changed. Functions, in a view, should only be placed inside directives like ng-init, ng-show, etc.
Most of the time if you want a function to run only once you can call if from the ng-init directive which runs once angular has been bootstrapped. However since this function deals with elements on the page you have to make sure everything is rendered. You can use angular.element(document).ready which is similar to jQuery's ready function:
angular.element(document).ready(function () {
var scope = angular.element(window.document.getElementById("tabsContainer")).scope();
scope.getDivs();
});
The second line gets the correct $scope of the controller wrapping the divs (I added the #tabsContainer id:
<div id="tabsContainer" ng-controller="TabsDemoCtrl">
<tabset vertical="true" type="navType">
<tab heading="Vertical 1"><div id="ciccio">Content 1</div></tab>
<tab heading="Vertical 2">Vertical content 2</tab>
</tabset>
</div>
Updated plunker here http://plnkr.co/edit/xkzcJfMFnmdfCQtOWEY0
Upvotes: 3