如何在AngularJS中制作自定义指令,等待ng-repeat进行渲染?
我遇到了什么问题:在li元素被渲染之前的指令init,所以DOM没有准备好,并且计算的块的高度不正确。
这是我的代码
AngularJS
.directive('navCollapse', function(){
return {
restrict: 'A',
scope: {
navItems: '=',
navScrollOn: '='
},
link: function($scope, $element, $attrs) {
var $navList = $element.find('ul'),
navItemsChildren = $navList.children('li'),
navItemsChildrenDefault = navItemsChildren.get(),
navItemsChildrenGet = navItemsChildren.get(),
showItems = ($scope.navItems !== undefined) ? $scope.navItems : 6,
showItemsOnScroll = ($scope.navItems !== undefined) ? $scope.navScrollOn : navItemsChildren.length,
isCollapsed = false,
calculateHeight = navItemsChildren.outerHeight() * showItems,
calculateFullHeight = navItemsChildren.outerHeight() * showItemsOnScroll;
$navList.wrap('<div class="links-wrap" style="max-height:'+ calculateHeight +'px"></div>');
function sortNav(element) {
element.sort(function(a,b){
var keyA = $(a).find('a').text();
var keyB = $(b).find('a').text();
if (keyA < keyB) return -1;
if (keyA > keyB) return 1;
return 0;
});
}
$element.find('.show-more').on('click', function(e) {
var linksWrap = $('.links-wrap');
if (isCollapsed === false) {
isCollapsed = true;
sortNav(navItemsChildrenGet);
$navList.empty();
$.each(navItemsChildrenGet, function(i, li){
$navList.append(li);
});
linksWrap.css({
'max-height' : calculateFullHeight + 'px',
'overflow' : 'auto'
});
} else {
isCollapsed = false;
$navList.empty();
$.each(navItemsChildrenDefault, function(i, li){
$navList.append(li);
});
linksWrap.css('max-height', calculateHeight+'px');
linksWrap.css('overflow', 'hidden');
}
});
}}})
HTML
<div class="links links-btn-more">
<div ng-controller="categoriesCtrl" nav-collapse nav-scroll-on="10" nav-items="4">
<h4>Categories</h4>
<hr>
<ul>
<li ng-repeat="cat in categories.aList">
<a ui-sref="collections({categoryId:cat.id})" title="">{{cat.name}} </a>
</li>
</ul>
<button class="btn show-more"></button>