我有一个使用 ng-repeat 的 div。
我从数组中的几个项目开始。
我想在渲染下一个项目之前强制渲染第一个项目。这样做的原因是因为每个div对高度的依赖
有办法吗?
<div class='listOne'>
<div ng-repeat='item in listOne'>{{item}}</div>
</div>
<div class='listTwo'>
<div ng-repeat='item in listTwo'>{{item}}</div>
</div>
JS
var myList = ['something', 'stuff', 'someOtherthing'];
var listOne = [];
var listTwo = [];
// decide which list to insert into
function decideListBasedOnHeight() { // returns array
var listOneElement = // reference to listOne element
var listTwoElement = // reference to listTwo element
if (listOneElement.offsetHeight > listTwoElement.offsetHeight ) // the height here is zero for both
return listTwo;
return listOne;
}
forEach (myList, function(value) {
decideBasedOnHeight().push(value);
});
问题示例:http://plnkr.co/edit/XxJTzNlnQrB7S7tQ0PBL?p=preview 第二个例子:http://plnkr.co/edit/3pzpsgmQ0vIM1e6nuEQG?p=preview
最佳答案
嗯,问得好。
你不能 forEach 一个数组,而是通过指令一步一步地推送它。见
<div ng-contoller="ctrl">
<div class='listOne'>
<div ng-repeat='item in listOne' count-height-and-push-next="listOneHeight">{{item}}</div>
</div>
<div class='listTwo'>
<div ng-repeat='item in listTwo' count-height-and-push-next="listTwoHeight">{{item}}</div>
</div>
</div>
.directive('countHeightAndPushNext', function(){
return{
restrict: 'A',
scope: true,
link: function(scope, element, attrs){
scope[attrs.countHeightAndPushNext] += element[0].outerHeigth;
scope.pushItem();
}
};
})
.controller('ctrl', function($scope){
$scope.myList = ['something', 'stuff', 'someOtherthing'];
$scope.listOne = [];
$scope.listOneHeight = 0;
$scope.listTwo = [];
$scope.listTwoHeight = 0;
var nextPushIndex = 0;
$scope.pushItem = function(){
if($scope.listOneHeight > $scope.listTwoHeight){
$scope.listTwo.push($scope.myList[nextPushIndex])
}else{
$scope.listOne.push($scope.myList[nextPushIndex]);
}
nextPushIndex++;
};
$scope.pushItem();
});
我真的不喜欢这个例子中的紧耦合,它绝对需要重构和重新制作,但这只是一个想法。可能不是最好的,但它应该有效。干杯。
关于javascript - AngularJS - 强制渲染/重新渲染/编译一个 ng-repeated div inside 指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24518253/