模板中带有 ng-if 的 angularjs 指令 [英] angularjs directive with ng-if in the template

查看:27
本文介绍了模板中带有 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.

我添加了一个 plunk 来演示:http://plnkr.co/edit/Gl7v8yJLevi664nUKcFY?p=预览

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

推荐答案

大多数指令实际上在 $watch() 中完成大部分逻辑.例如 ng-if 将在它的属性上设置一个监视,然后在它发生变化时渲染/删除 dom.Watches 在一个摘要周期内执行,所以即使指令已经被编译和链接,watch 还没有运行来确定它是否应该显示 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 呈现之后,您也会冒 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 添加到您的模板中.

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天全站免登陆