我有一個定義的指令:子元素在指令
$(function() {
angular.module(['myApp']).directive('rootSlider', function() {
return {
restrict: 'E',
template: '<ul><li ng-repeat="item in items"><img ng-src="{{item.url}}" /></li></ul>',
scope: {
items: '='
},
replace: true,
compile: function ($templateElement, $templateAttributes) {
return function ($scope, $element, $attrs) {
var $scope.items.length //expect 2, get 2
var numChildren $element.children().length //expect 2, get 0
};
}
};
});
});
雖然$scope.items
酒店有2項,並在最後呈現的DOM有兩個<li>
元素,在鏈接功能$element
尚未有孩子。
在角度生命週期的哪個點可以得到完全呈現的元素(我的意圖是在這裏使用jQuery滑塊插件)。
標記是
<root-slider items="ModelPropertyWithTwoItems"></root-slider>
UPDATE:
我能得到這個與$ watchCollection的組合和$ evalAsync正常工作。
$(function() {
angular.module(['myApp']).directive('rootSlider', ['$timeout', function ($timeout) {
return {
restrict: 'E',
template: '<ul class="bxslider"><li ng-repeat="item in items"><img ng-src="{{item.url}}" /></li></ul>',
scope: {
items: '='
},
compile: function ($templateElement, $templateAttributes) {
return function ($scope, $element, $attrs) {
$scope.$watchCollection('items', function (newCollection, oldCollection) {
if ($scope.slider) {
$scope.$evalAsync(function() {
$scope.slider.reloadSlider();
});
}
else {
$scope.$evalAsync(function() {
$scope.slider = $element.find('.bxslider').bxSlider();
});
}
});
};
}
};
} ]);
});
腕錶系列閃光一次,在指令初始化(因爲它是一個集合,你不能比較的NEWVALUE和屬性oldValue,所以我最終將滑塊對象到獲取的實例創建的$範圍
我使用$ evalAsync推遲jQuery代碼的執行,目前爲止所有瀏覽器都避免閃爍(這似乎是在$ timeout(function(){},0)之前運行的。)
上面的解決方案可能可以簡化,只需返回一個鏈接函數(而不是一個編譯函數,結果是不必要的)。
這可以工作,但會創建一個臨時顯示無格式元素的情況。似乎會有一個更具體的框架鉤。 –
$ timeout對此非常普遍 - 但我完全明白它看起來很糟糕。我很困惑,你看到一個你以前沒有看過的閃光燈,因爲這不應該延遲加載圖像/模板。還有其他的東西在等着嗎?這是一個演示,延遲時間爲2秒,但模板正常加載:jsfiddle.net/csnGL/2 – KayakDave
將此標記爲答案。 $ watch解決方案沒有具體解決該問題(儘管它很有幫助),並且鏈接到您發佈的功能請求導致我到$ evalAsync。謝謝! –