我们什么时候知道 Angular 中元素的实际宽度? [英] When do we know the actual width of an element in Angular?
问题描述
我正在尝试创建一个将 div 居中的指令.
I'm tring to create a directive that will center a div.
到目前为止,我有这个代码:
So far, I have this code:
app.directive("setcenter", function () {
return {
scope:{
setcenter: '='
},
link: function (scope, element, attrs) {
scope.$watch('setcenter', function (newValue) {
if (newValue == true) {
var width = element.width();
element.css('position', 'absolute');
element.css('top', '80px');
element.css('left', '50%');
element.css('z-index', '200');
element.css('margin-left', '-' + width / 2 + 'px');
}
});
}
}
});
问题是元素的宽度.该指令的重点是使用该指令的 div 没有设置宽度.我希望这个指令计算出宽度并使 div 居中.
The problem is the width of the element. The whole point for this directive is that the div that uses this directive, don't have a width set. I want this directive to figure out the width and center the div.
我遇到的问题是,当指令被调用时,div的实际宽度还不知道.当我在我的情况下使用它时,div 是 800px,但是当页面加载完成时,div 是 221px.
The problem I encounter is that when the directive is invoked, the actual width of the div is not yet known. When I use this in my situation, the div is 800px, but when the page is finished loading, the div is 221px.
那么,我该怎么做才能等到知道 div 的实际宽度?
So, what can I do to wait till the actual width is known of the div?
推荐答案
首先,我只在为指令定义了控制器而不是一个链接功能.所以在链接函数中定义它可能会导致不同的行为,但我建议你先在那里尝试,如果你不能让它工作,然后切换到使用控制器.
First, I only have used this logic when I defined a controller for a directive rather than a link function. So defining it in a link function instead may cause different behavior, but I suggest you try it there first and if you can't get it to work then switch to using a controller.
据我所知,您需要进行的唯一更改是将 $scope 更改为作用域调用,将 $element 更改为元素,因为依赖项注入的对象成为标准链接函数参数.
As far as I can tell, the only change you would need to make this work would be to change $scope to scope calls and $element to element since the dependency injected objects become standard link function parameters.
$scope.getElementDimensions = function () {
return { 'h': $element.height(), 'w': $element.width() };
};
$scope.$watch($scope.getElementDimensions, function (newValue, oldValue) {
//<<perform your logic here using newValue.w and set your variables on the scope>>
}, true);
$element.bind('resize', function () {
$scope.$apply();
});
在阅读了一个非常相似的关于观察 $window 而不是当前元素的用法后,我想到了这种用法,原始作品可以在这里找到.
The idea for this usage came to me after reading a very similar type of usage about watching the $window rather than the current element, the original work can be found here.
这篇关于我们什么时候知道 Angular 中元素的实际宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!