【问题标题】:Weird precedence of angular directive linking function in DOM manipulation (after ng-repeat)DOM操作中角度指令链接函数的奇怪优先级(在ng-repeat之后)
【发布时间】:2015-04-21 22:23:29
【问题描述】:

我对这个有角度的东西(以及一般的 web-dev)是新手,但我遇到了一个奇怪的行为,即自定义指令的角度链接函数如何更改 DOM。更具体地说,该指令(使用 ng-repeat)创建模板的多个实例:这些实例可以通过 document.getElementsByClassName() 以某种方式访问​​,但不能在 angular 或 jquery 内部访问。

我的 index.html 和 group-widgets.html(包含模板)也是:

<div class="groups_panel">
    <group-widgets class="col-md-12" style="margin-top:60px;"></group-widgets>
</div>

<div class="col-md-6 comment" ng-repeat="group in gWidget.groups">
    <div ...</div>
</div>

我的 app.js 是这样的:

(function(){
    var app = angular.module('pm',[]);
    app.directive('groupWidgets',function(){
        return{
            restrict: 'E',
            templateUrl: 'group-widgets.html',
            controller:function($scope){
                this.groups = allGroups;
                console.log($scope);
                console.log("Wait till renders...");                
            },
            controllerAs: 'gWidget',
            link: function(scope, element, attributes, parentCtrl){
                console.log("LINKED!");
                console.log(document.getElementsByClassName("comment"));
                console.log(element.html());
                console.log($(".comment"));
                console.log("END");
            }
        };
    });
})();

allGroups 变量是一个数组,其元素 ng-repeat 实例化。 使用 chrome 开发工具运行它后,我得到: Screenshot(检查内部 LINKED! 和 END)。

很明显,在链接功能期间,由 ng-repeat 创建的 DOM(如屏幕截图所示的四个实例)可通过 getElementsByClassName() 获得,但不能在角度元素对象中使用,也不能在使用 jQuery 的整个 DOM 中使用!

我已经解决了其他问题 (Calling a function when ng-repeat has finished.,AngularJS: Linking to elements in a directive that uses ng-repeat) 中描述的问题,但我无法理解指令链接功能的工作顺序以及为什么会发生这种情况。显然我做错了什么。你能帮我澄清一下这个问题吗?

提前致谢。

【问题讨论】:

  • 什么是allGroups编辑你也可以尝试document.getElementsByClassName("comment").length作为你的第二个查询并确认它是0还是4?
  • 嗨。 @John Drouhard 不,但很有帮助;还说明链接功能 - “它在模板被克隆后执行”增加了我的困惑。
  • @Ed Hinchliffe allGroups 变量是一个数组,其元素 ng-repeat 实例化;你说得对:它的 0 进一步增加了我的困惑。但是解决方案开始出现,罪魁祸首是 HTMLCollection,它是“实时”的。

标签: jquery angularjs dom directive ng-repeat


【解决方案1】:

这里发生的事情可能会让您感到困惑,因为 Chrome 控制台在“查看时间”而不是在“日志时间”评估记录的对象。

检查的简单方法是执行以下操作:

 console.log(document.getElementsByClassName("comment").length); // will be 0

因此,您从document.getElementsByClassName 获得的 HTMLCollection 在您查看日志时进行评估,因此包含 4 个 div。



(*) 我不确定究竟是什么构成了“查看”,或者实际的触发器是什么,但它没有记录。

【讨论】:

  • 感谢您的及时回复。我无法找到有关“查看时间”VS“日志时间”的任何内容,但是从这里link 我知道在执行链接功能时HTMLcollection 是空的(因此长度==0)并且在实时收集更新的日志时间。所以我从一开始就猜是菜鸟问题:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-16
  • 1970-01-01
  • 2016-07-15
  • 1970-01-01
相关资源
最近更新 更多