DOM操作中角度指令链接函数的奇怪优先级(在ng重复之后)



我对这个角度的东西(以及一般的web开发)是新手,但我遇到了一个奇怪的行为,涉及到自定义指令的角度链接函数如何更改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重复实例化。在用chrome开发工具运行它之后,我得到:屏幕截图(检查内部链接!和结束)。

很明显,在链接函数期间,ng repeat创建的DOM(屏幕截图中显示的四个实例)可以通过getElementsByClassName()使用,但不在angular元素对象内,也不在使用jQuery的整个DOM内!

我已经解决了其他问题中描述的问题(当ng重复完成时调用函数。,AngularJS:链接到使用ng重复的指令中的元素),但我无法理解指令链接函数的工作顺序以及为什么会发生这种情况。显然我做错了什么。你能帮我澄清一下这个问题吗?

提前谢谢。

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

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

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

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



(*)我不确定"查看"的具体组成,也不确定实际的触发器是什么,但它不是日志记录。

最新更新