Reputation: 7781
I need to call an angular controller function using ng-init once the element is visible...
Ex:
//Do not call function as element is hidden.
<div style="display: none" ng-init="function()"></div>
//Call function as element is visible.
<div style="display: block" ng-init="function()"></div>
How to check with ng-init and call function accordingly?
Upvotes: 1
Views: 4743
Reputation: 17878
Use ng-if
<div id="myDiv" ng-if="show" ng-init="init()"></div>
ng-if
does not place the element into the DOM as long as its expression evaluates to false.
Demo: plnkr (init function is run when div is shown after 2 seconds)
EDIT:
Apparently the display-property is set from outside of angular's context. I'm pretty sure it will be hard to make it work via the style attribute. The best suggestion I could come up with for that is to first get a reference to the div and then use $apply
to make ng-if
's expression true.
With JQuery:
var scope = angular.element($('#myDiv')).scope();
scope.$apply(function() {
scope.show = true;
});
That uses angular.element
to get a reference to the scope, and then uses $apply
to change a property in a way that will trigger Angular's dirty-checking and make the div appear.
Upvotes: 2