【发布时间】: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