I have an defined a directive:
$(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
};
}
};
});
});
Although the $scope.items
property has 2 items, and in the final rendered DOM there are two <li>
elements, in the link function $element
does not yet have children.
At what point in the angular lifecycle can I get the completely rendered element (my intention is to use a jQuery slider plugin here).
The markup is
<root-slider items="ModelPropertyWithTwoItems"></root-slider>
UPDATE:
I was able to get this to work correctly with a combination of $watchCollection and $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();
});
}
});
};
}
};
} ]);
});
Watch collection fires once on directive initialization (since it is a collection, you can't compare the newValue and oldValue, so I ended up adding the slider object to the $scope that gets created for the instance of the directive.
I use $evalAsync to defer execution of the jQuery code which (so far) is proving to avoid flicker on all browsers (it seems to run before $timeout(function(){}, 0).
The solution above could probably be simplified by just returning a link function (rather than a compile function, which turned out to be unneccessary).