在模板中使用ng-if的angularjs指令 [英] angularjs directive with ng-if in the template

查看:60
本文介绍了在模板中使用ng-if的angularjs指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用ng-if内部模板的指令。奇怪的是,提供给link函数的元素没有展开ng-if代码,它只是ng-if的注释行。到处玩,我发现通过将我的链接代码包装在$ timeout中似乎可以使它工作,但我想知道这是不是正确的方法来实现它......更多的是,为什么会发生这种情况。

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.

我添加了一个插件来演示: http://plnkr.co/edit/Gl7v8yJLevi664nUKcFY?p=preview

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

推荐答案

大多数指令实际上做得最多他们在$ watch()中的逻辑。例如,ng-if将在其属性上设置监视,然后在更改时渲染/删除dom。手表在摘要周期中执行,因此即使已经编译和链接了指令,手表还没有运行以确定它是否应该显示if。

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.

编辑:

您应该考虑一下您实际在做什么确保它是你想要的。请记住, ng-if 是动态的。因此,根据items数组是否为空,它可能随时被删除或添加。

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.

这意味着即使你设法推迟你的dom操作直到if渲染之后,你也会冒险离开并回来(在这一点上)您的css代码将不会再次运行)。

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).

更好的方法是设置手表并在手表中添加你的css,或者更好的是,使用ng-class并在你的css中添加css模板。

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.

这篇关于在模板中使用ng-if的angularjs指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆