[英]angularjs find properties of div in directive
new to angular, new to stackoverflow. 对角度来说是新手,对于堆栈溢出来说是新手。 been trying to solve this for days.
几天来一直试图解决这个问题。 here is my problem:
这是我的问题:
I want to center a group of boxes. 我想把一组盒子居中。
Is there a way to get access to properties of div's (with id or class names) and manipulate them in a directive? 有没有一种方法可以访问div的属性(具有ID或类名)并在指令中对其进行操作?
in my html I am creating divs with ng-repeat, the divs are the boxes that are displayed. 在我的HTML中,我正在使用ng-repeat创建div,这些div是显示的框。 I have a directive that I, for now, am trying to use to find and manipulate properties of the div's/directives in the html, however I can't seem to do this.
我有一个指令,我目前正在尝试使用它来查找和操纵html中div /指令的属性,但是我似乎无法做到这一点。
I have googled a lot and have found similar issues but nothing that seems to work in my code. 我在Google上搜索了很多,发现了类似的问题,但是似乎在我的代码中没有任何效果。
here's a fiddle: 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'));
}
};
});
Thank you for any help provided. 感谢您提供的任何帮助。
The reason is because ng-repeat changes the DOM, the children elements are not available during directive compilation. 原因是因为ng-repeat更改了DOM,子元素在指令编译期间不可用。 so a $watch is needed on child elements.
因此在子元素上需要一个$ watch。
This notifies the directive that child elements are added and then perform operation on them. 这会通知指令添加了子元素,然后对其执行操作。
The $watch must skip the nodeType which is "comment:(type 8)" $ watch必须跳过nodeType,它是“ comment:(type 8)”
here is the working fiddle: http://jsfiddle.net/3m87R/3/
这是工作的小提琴: http : //jsfiddle.net/3m87R/3/
The part in link: 链接中的部分:
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');
}
}
});
}
You are close! 你近了! I was able to get the directive working in one of my test fiddles.
我能够在我的测试小提琴之一中使指令生效。 Take a look.
看一看。
$(element).css('border', '1px solid red');
$(element).css('text-align', 'center');
See this fiddle where I have a sample of your directive. 看到这个小提琴,那里有您的指令示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.