Mar*_*man 10 javascript angularjs
我有一个问题 - 我忘记了如何编码!我有一个angularJS指令,它位于父包装器标签(DIV)上,在我的指令中我想循环遍历子节点(第一个子DIV).我有以下内容
<div data-check-attributes>
<div data-ng-repeat="user in Users" data-id="{{ user.ID }}" data-ng-click="doSomething(user.ID)" data-new="{{ user.newUser }}" class="">
<div> {{ user.userName }} </div>
<div> {{ user.userAge }} </div>
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
现在在我的指令中我想循环遍历第一个子div(可能有很多这些,但我在加载的视图中看到10个用户)并在我的指令中执行某些检查和修改,使用数据属性,$ location对象和可能还有更多...但是我不记得如何遍历第一个子div,我似乎得到了我尝试过的所有错误...到目前为止我有这个,这不起作用!在下面的示例中,我只想将第一个子节点的data-id写入控制台
.directive('checkAttributes', function ($location) {
return{
restrict: 'A',
link: function (scope, element) {
// will use $location later
console.log(angular.element(element)[0]); // this outputs the HTML
console.log(angular.element(element)[0].children().length); // this errors, TypeError: object is not a function
for (var i = 0; i < angular.element(element)[0].children.length; i++) {
console.log(angular.element(element)[0].children[i].getAttribute('data-id'));
}
}
};
});
Run Code Online (Sandbox Code Playgroud)
我很困惑......请帮忙!
如果您正在尝试访问childrenHTMLElement的属性,那么您应该像属性一样阅读它.
另一件事是它element已经是一个实例,angular.element所以不需要再次包装它:
console.log(element[0]); // DOM element
console.log(element[0].children.length);
Run Code Online (Sandbox Code Playgroud)
但是,angular.element对象提供了一组便利方法.这些方法复制了一些jQuery的方法,包括$.fn.children方法.在这种情况下,您也可以这样做
console.log(element); // angular.element instance
console.log(element.children().length);
Run Code Online (Sandbox Code Playgroud)
最后,还有一个警告:ngRepeat将在自定义指令之后呈现其元素,因此您无法访问children集合.最简单的解决方法是将代码包装到$timeout服务中,这将在下一个摘要周期中执行您的逻辑,ngRepeat完成后保证:
app.directive('checkAttributes', function($location, $timeout) {
return {
restrict: 'A',
link: function(scope, element) {
// will use $location later
$timeout(function() {
for (var i = 0; i < element[0].children.length; i++) {
console.log(element[0].children[i].getAttribute('data-id'));
}
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
演示: http ://plnkr.co/edit/oEOSY2e2E0mmLDQOHbff?p =preview