I'm trying to implement the jQuery multiselect plugin using a directive inside my app. Here' the select element:
<select multiple
ng-model="data.partyIds"
ng-options="party.id as party.name for party in parties"
xs-multiselect="parties">
</select>
The model parties model is loaded through $http. The multiselect plugin parses the option elements inside the select and generates the nice multi select.
Is there a way to detect when the select element is populated with options so I can tell the multiselect plugin to update its data?
Here's my directive:
machineXs.directive("xsMultiselect", function() {
return {
restrict: "A",
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
element.multiselect().multiselectfilter();
scope.$watch(scope[attrs["xsMultiselect"]], function() {
// I tried watching but it doesn't help
element.multiselect('refresh');
element.multiselectfilter("updateCache");
});
}
}
});
As discussed in the comments, use
scope.$watch(attrs.xsMultiselect, ...)
I'm not sure when the watch triggers vs when ngOptions updates the DOM. If you find that the watch is triggering too early, you can try using $evalAsync() or $timeout(). $evalAsync will execute later, but before the DOM renders. $timeout() will execute later, after the DOM renders.
scope.$watch(attrs.xsMultiselect, function() {
scope.$evalAsync(function() {
element.multiselect('refresh');
element.multiselectfilter("updateCache");
});
});
or, after the DOM renders:
scope.$watch(attrs.xsMultiselect, function() {
$timeout(function() {
element.multiselect('refresh');
element.multiselectfilter("updateCache");
});
});