简体   繁体   English

AngularJS - 从元素中动态删除指令

[英]AngularJS - dynamically remove directive from element

What is the proper way to dynamically add or remove directive from compiled and linked element? 从编译和链接元素动态添加或删除指令的正确方法是什么?

I have a page that has bunch of inputs there (the list is pretty long, so i want to come up with a general solution). 我有一个页面,有很多输入(列表很长,所以我想提出一个通用的解决方案)。 What i want to do is to disable all the inputs if specific flag set. 我想要做的是如果设置了特定标志,则禁用所有输入。 I can do this by using jQuery's element.prop('disabled', true). 我可以通过使用jQuery的element.prop('disabled',true)来做到这一点。

The problem of such approach is that if any of inputs have ng-disabled or ng-enabled directives attached, then on any their expression modification they will override previously set 'disabled' property. 这种方法的问题在于,如果任何输入都附加了ng-disabled或ng-enabled指令,那么在任何表达式修改时,它们将覆盖先前设置的'disabled'属性。 But I want them to not override my global flag. 但我希望他们不要覆盖我的全球旗帜。

I came up with the solution to add another bunch of watchers for ng-disabled or ng-enabled expression, but it seems to be not the best approach. 我想出了一个解决方案,为ng-disabled或ng-enabled表达添加另一组观察者,但它似乎不是最好的方法。

What I want to do, is to remove most of directives attached to the element and set appropriate attributes myself. 我想要做的是删除附加到元素的大多数指令并自己设置适当的属性。 But if I recompile and relink the element, and then replace it in the document, then I will get a memory leak, as the old element will be deattached from the DOM document tree, and will remain in memory. 但是如果我重新编译并重新链接元素,然后在文档中替换它,那么我将得到内存泄漏,因为旧元素将从DOM文档树中删除,并将保留在内存中。 I cannot destroy element's scope either, because those elements basically use whole page's main scope. 我也无法破坏元素的范围,因为这些元素基本上使用整个页面的主要范围。

You can try something like 你可以尝试类似的东西

<div ng-show="someBoolean" >Some text or nested element</div>

or instead of "someBoolean" you can attach a function that resolves to a boolean. 或者代替“someBoolean”,你可以附加一个解析为布尔值的函数。 To set your boolean you could attach a ng-click to your input that updates your model/boolean value 要设置布尔值,您可以在输入中附加ng-click以更新模型/布尔值

<button type="button" ng-click="setBoolean()">Some text or nested element </button>

Because of angulars two way data binding the ng-show will be updated upon completion of the next digest cycle 由于角度,双向数据绑定ng-show将在下一个摘要周期完成时更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM