AngularJS观看DOM变化 [英] AngularJS watch DOM change
问题描述
我有一个自动旋转木马
指令,它通过链接元素的儿童迭代
I have one auto-carousel
directive which iterates through the linked element's children.
但尚未加载到DOM孩子们,因为他们的 NG-如果
前夫pressions尚未解析。
The children however are not yet loaded in the DOM, because their ng-if
s expressions have not been parsed yet.
我怎样才能确保母体指令知道有过改变它的DOM树?
How can I make sure the parent directive knows there have been changes to it's DOM tree?
<ul class="unstyled" auto-carousel>
<li class="slide" ng-if="name">{{name}}</li>
...
<li class="slide" ng-if="email">{{email}}</li>
</ul>
我可以使用 $超时
但感觉不可靠的。我还可以使用 NG-节目
而不是 NG-如果
但是,这并不回答这个问题,而不是我所需要的
I could use $timeout
but that feels unreliable. I could also use ng-show
instead of ng-if
but that does not answer the question and not what I need.
推荐答案
因此,这里是我落得这样做:
So here's what I ended up doing:
我发现,你可以传递给 $范围的功能。$看
。从那里,它是pretty直白地回到你想要观看更改除权pression的价值。它将工作完全一样传递一个密钥字符串为属性的范围。
I discovered you could pass a function to $scope.$watch
. From there, it's pretty straightforward to return the value of the expression you want to watch for changes. It will work exactly like passing a key string for a property on the scope.
link: function ($scope, $el, $attrs) {
$scope.$watch(
function () { return $el[0].childNodes.length; },
function (newValue, oldValue) {
if (newValue !== oldValue) {
// code goes here
}
}
);
}
我看子节点
,而不是孩子
,因为子节点
列表元素持有以及的文本节点和注释。这是无价的,因为角用来指示注释占位符如 NG-重复
, NG-如果
, NG-开关
和 NG-包括
它们执行transclusion和修改DOM,而孩子
仅持有元素。
I am watching childNodes
, not children
, because the childNodes
list holds elements as well as text nodes and comments. This is priceless because Angular uses comment placeholders for directives like ng-repeat
, ng-if
, ng-switch
and ng-include
which perform transclusion and alter the DOM, while children
only holds elements.
这篇关于AngularJS观看DOM变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!