Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
166
rated 0 times [  167] [ 1]  / answers: 1 / hits: 9138  / 11 Years ago, fri, january 3, 2014, 12:00:00

I'm building a directive that utilizes an ng-if inside of it's template. What's strange is that the element provided to the link function does not have the ng-if code expanded, it is only a comment line for the ng-if. Playing around, I found that by wrapping my link code in a $timeout seems to get it to work, but I am wondering if that is not the correct way of going about it....and more so, why is this happening.



I've added a plunk to demonstrate: http://plnkr.co/edit/Gl7v8yJLevi664nUKcFY?p=preview


More From » angularjs

 Answers
5

Most directives actually do most of their logic in a $watch(). For example ng-if will setup a watch on it's attribute, and then render/remove the dom when that changes. Watches execute during a digest cycle, so even though directives have been compiled and linked, the watch hasn't run yet to determine whether it should show the if or not.



EDIT:



You should probably think about what you are actually doing to make sure if it's what you want. Keep in mind that the ng-if is dynamic. And so at any time it might get removed or added based on whether the items array is empty or not.



This means that even if you manage to defer your dom manipulation until after the if is rendered, you run the risk of the if going away and coming back (at which point your css code will not be run again).



A much better way to do this would be to setup a watch and add your css in a watch, or better still, use ng-class and add the css in your template.


[#49041] Thursday, January 2, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daijab

Total Points: 60
Total Questions: 99
Total Answers: 110

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
;