我已经为你的问题的解决方案。首先我会向你解释我所做的以及为什么我这样做。
Angular的一个基本原则是,你应该避免在你的控制器中处理div元素之类的DOM元素,而是在指令中完成与DOM元素相关的大部分事情。
指令允许您将函数绑定到特定的dom元素。在这种情况下,你想要绑定一个函数到你的第一个div,它获取元素的高度和宽度并将它暴露给另一个元素。我在下面评论了我的代码,以说明我是如何实现这一目标的。
app.directive('master',function() { //declaration; identifier master
function link(scope, element, attrs) { //scope we are in, element we are bound to, attrs of that element
scope.$watch(function(){ //watch any changes to our element
scope.style = { //scope variable style, shared with our controller
height:element[0].offsetHeight+'px', //set the height in style to our elements height
width:element[0].offsetWidth+'px' //same with width
};
});
}
return {
restrict: 'AE', //describes how we can assign an element to our directive in this case like <div master></div
link: link // the function to link to our element
};
});
现在,我们的范围可变样式应该包含与我们的“主”元件的电流的宽度和高度的物体即使我们主元件的大小变化。
接下来,我们要应用这种风格到另一个元素,我们可以实现像这样:
<span master class="a">{{content}}</span>
<div class="b" ng-style="style"></div>
正如你所看到的跨度上面是我们在div主元素是我们的“奴隶”,这将始终具有与主人相同的宽度和高度。 ng-style="style"
意味着我们将包含在我们的作用域变量scope中的css样式添加到span中。
我希望你能理解我为什么以及如何得到这个解决方案,here is a plnkr,演示了我的解决方案。
感谢这么多如此详细的解答 – lesek 2015-02-10 08:09:18
这是不会,如果你有更多的工作而不是页面上的其中一个 – 2017-10-28 03:34:21