Reputation: 25282
I have a table that renders rows with ng-repeat
. Inside one of the cells there is a select that is rendered with ng-options
.
<tr ng-repeat="item in data.items" repeat-done>
<td >
...
<select class="selectpicker"
ng-model="person" ng-options="person.Surname for person in data.Persons track by person.Id">
<option value="">Introduce yourself...</option>
</select>
...
<td>
</tr>
When repeat is done I need to turn select into bootstrap-select (a nice looking dropdownlist). So after a little bit of researching I added the following directive:
app.directive('repeatDone', function () {
return function (scope, element, attrs) {
if (scope.$last) {
setTimeout(function() { $('.selectpicker').selectpicker(); }, 1);
};
};
});
which is specified at tr (see above).
It works. But I am a little bit worried whether there is a chance it will not work on slow PC/tablet/etc. As I understand AngularJS has an asynchronous nature. So while the last element of ng-repeat
is being processed, it is still possible ng-options
for this element (or may be for some previous element too) is not rendered. Or am I paranoiac?
Upvotes: 0
Views: 358
Reputation: 3893
You shouldn´t synchronize your directives using timeout. A lot of problems can appear.
You can use the option priority to sort when your directives are going to be used. Directives are executed on descendant order.
ngRepeat has priority 1000 (https://docs.angularjs.org/api/ng/directive/ngRepeat) select has priority 0 (https://docs.angularjs.org/api/ng/directive/select)
If you declare your directive with a negative priority it will execute after ng-options.
app.directive('repeatDone', function () {
return {
priority: -5,
link: function (scope, element, attrs) {
$('.selectpicker').selectpicker();
}
}
});
According to Angular documentation:
priority
When there are multiple directives defined on a single DOM element, sometimes it is necessary to specify the order in which the directives are applied. The priority is used to sort the directives before their compile functions get called. Priority is defined as a number. Directives with greater numerical priority are compiled first. Pre-link functions are also run in priority order, but post-link functions are run in reverse order. The order of directives with the same priority is undefined. The default priority is 0.
https://docs.angularjs.org/api/ng/service/$compile
Upvotes: 1