1

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?

4
  • What makes the element visible? I don't see any Angular code for that. That's where you should call function() Commented Aug 20, 2014 at 7:06
  • 2
    ng-init is called as soon as the div is rendered, so use ng-if conditional statement to render or not render the div Commented Aug 20, 2014 at 7:08
  • @RGraham Its made visible in an external javascript file not in angular controller. Is there any way to watch for change of element style? Commented Aug 20, 2014 at 7:09
  • @Govan No. If it's external javascript, it should throw some sort of event. Use a directive and bind onto that event using .on Commented Aug 20, 2014 at 7:10

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This would be fine, but OP is using an external Javascript which sets the display property directly, so this won't work.
Right.. that part wasn't in the question when I started typing :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.