Angular 新手,StackOverflow 新手。几天来一直试图解决这个问题。这是我的问题:
我想将一组盒子居中。
有没有办法访问 div 的属性(带有 id 或类名)并在指令中操作它们?
在我的 html 中,我使用 ng-repeat 创建 div,div 是显示的框。我有一个指令,目前正在尝试使用它来查找和操作 html 中 div/指令的属性,但是我似乎无法执行此操作。
我用谷歌搜索了很多,发现了类似的问题,但似乎没有任何东西可以在我的代码中工作。
这是一个小提琴:http://jsfiddle.net/3m87R/ http://jsfiddle.net/3m87R/
app.directive('someBoxes', function()
{
return function(scope, element, attrs)
{
element.css('border', '1px solid white');
//element.css('width', '200px');
var body = angular.element(document).find('.bookitem');
console.log(body[0].offsetWidth);
if(scope.$last)
{
//console.log("element name is: " + element.attr("class"));
//console.log("element is: " + element);
//console.log($(".bookitem").children("div").attr("class"));
//console.log($('.container').children('div').attr('class'));
}
};
});
感谢您提供的任何帮助。
原因是因为ng-repeat改变了DOM,子元素不可用
在指令编译期间。
所以子元素需要一个 $watch 。
这通知指令添加了子元素,然后对它们执行操作。
$watch 必须跳过节点类型“comment:(type 8)”
这是工作小提琴:http://jsfiddle.net/3m87R/3/ http://jsfiddle.net/3m87R/3/
链接中的部分:
link: function ($scope, element, attrs, controller) {
$scope.$watch(element.children(),function(){
var children = element.children();
for(var i=0;i<children.length;i++){
if(children[i].nodeType !== 8){
angular.element(children[i]).css('background', 'orange');
}
}
});
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)