AngularJS 观察 DOM 变化 [英] AngularJS watch DOM change

查看:27
本文介绍了AngularJS 观察 DOM 变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 auto-carousel 指令,它遍历链接元素的子元素.

I have one auto-carousel directive which iterates through the linked element's children.

然而,孩子们还没有加载到 DOM 中,因为他们的 ng-if 的表达式还没有被解析.

The children however are not yet loaded in the DOM, because their ng-ifs 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>

我可以使用 $timeout 但这感觉不可靠.我也可以使用 ng-show 而不是 ng-if 但这不能回答问题,也不是我需要的.

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.

推荐答案

所以这是我最终做的:

我发现您可以将函数传递给 $scope.$watch.从那里,返回要监视更改的表达式的值非常简单.它的工作方式与为作用域上的属性传递键字符串完全一样.

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
      }
    }
  );
}

我在看childNodes,而不是children,因为childNodes 列表包含元素以及 文本节点和评论.这是无价的,因为 Angular 对 ng-repeatng-ifng-switchng-include 等指令使用注释占位符 执行嵌入和改变 DOM,而 children 只保存元素.

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屋!

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