通过指令在 ng-repeat 中获取 AngularJS 中当前元素的宽度
Getting current element's width in AngularJS within ng-repeat via directive
没有错误,但我的指令没有输出正确的宽度值 (clientWidth)。
以下情况:
这是我的数据,3条(摘录app.js):
$scope.data = [
"Account Information",
"Contact Person",
"T&C"
];
这就是观点(节选index.html):
<div ng-repeat="item in data" class="box" get-width="">
{{item}}
</div>
这是指令(摘录app.js):
.directive('getWidth',function(){
return {
link: function (scope, element){
console.log("Current Element's Width",element[0].clientWidth);
}
}
那是样式表,框有不同的宽度,它们已经正确呈现:
.box {
float: left;
margin-right: 10px;
padding: 10px;
border: 1px solid grey;
}
而且如你所见,第一个元素的宽度(clientWidth)是155:
但我得到了输出(3 次):当前元素的宽度 79,我期待 3 个正确的宽度值。
我的错误是什么?也许这是一个时间问题,在通过指令获取宽度时 div 中的文本没有渲染?
你是对的,这是一个时间问题。注入 angulars $timeout,你会得到你想要的结果。
.directive('getWidth',function($timeout){
return {
link: function (scope, element, attr){
$timeout(function(){
console.log("Current Element's Width",element[0].clientWidth);
})
}
}
});
没有错误,但我的指令没有输出正确的宽度值 (clientWidth)。
以下情况:
这是我的数据,3条(摘录app.js):
$scope.data = [
"Account Information",
"Contact Person",
"T&C"
];
这就是观点(节选index.html):
<div ng-repeat="item in data" class="box" get-width="">
{{item}}
</div>
这是指令(摘录app.js):
.directive('getWidth',function(){
return {
link: function (scope, element){
console.log("Current Element's Width",element[0].clientWidth);
}
}
那是样式表,框有不同的宽度,它们已经正确呈现:
.box {
float: left;
margin-right: 10px;
padding: 10px;
border: 1px solid grey;
}
而且如你所见,第一个元素的宽度(clientWidth)是155:
但我得到了输出(3 次):当前元素的宽度 79,我期待 3 个正确的宽度值。
我的错误是什么?也许这是一个时间问题,在通过指令获取宽度时 div 中的文本没有渲染?
你是对的,这是一个时间问题。注入 angulars $timeout,你会得到你想要的结果。
.directive('getWidth',function($timeout){
return {
link: function (scope, element, attr){
$timeout(function(){
console.log("Current Element's Width",element[0].clientWidth);
})
}
}
});