2016-09-26 64 views
1

這是我的代碼爲什麼不能在指令的鏈接函數中編譯?

// index.html 
<my-slider items="items"></my-slider> 

// slider.tpl.html 
<ul> 
    <li ng-repeat="item in items"> // items.length = 10 
    <my-thumb my-data="item"></my-thumb> 
    </li> 
</ul> 



// slider.directive.js 
angular.module('app') 
.directive('mySlider', function() { 
    return { 
    restrict: 'E', 
    templateUrl: 'slider.tpl.html', 
    scope: { 
     items: '=' 
    }, 
    link: function (scope, elem, attrs) { 
     console.log(scope.items); // print [{...},{...},{...}.....] 
     var elem.find('ul').css('width', _.sumBy(elem.find('li'), function (o) { $(o).width(); })); 

     // but 
     console.log(elem.find('li').size()); // print => 0 ???? why is 0? 
    } 
    }; 
}); 

我想整個寬度設置爲一個UI元素,但這種

elem.find('li').size() = 0 

爲什麼是空的?

回答

1

你需要讓ng-repeat渲染使用$timeout第一

嘗試這樣的代碼將無法運行,直到下一次消化

.directive('my-slider', function ($timeout) { 
    return { 
    //..... 
    link: function (scope, elem, attrs) { 
     $timeout(function(){ 
      console.log(elem.children().length) 
     }); 
    } 
}) 

DEMO

+0

感謝,.....在類似的情況下,它是否總是使用'​​$ timeout'? –

+0

如果您需要渲染子元素...是的。或者,您可以使用子指令的$ last屬性將事件發送給父項或在父項中觸發一個函數。如果你將要改變'ng-repeat'中的數據,這可能更實用 – charlietfl

相關問題