Mateus Vitali Mateus Vitali - 1 month ago 14
AngularJS Question

AngularJS Check if a select's options (with filter) changed

I have a custom directive, which is restricted as attribute, and works on select elements to make them more styleable (using jquery select-bootstrap).

Currently there isn't a proper way to check/watch if the options with filter of the select have been changed.

e.g.

<label>First Select</label>
<select ng-model="vm.myFirstModel"
ng-options="hour.id as hour.label for hour in vm.hours" selectpicker> </select>

<label>Second Select</label>
<select ng-model="vm.mySecondModel"
ng-options="hour.id as hour.label for hour in vm.hours | filter:vm.filterHours(vm.myFirstModel)" selectpicker>
</select>


My directive

angular.module('VAdmin.theme')
.directive('selectpicker', selectpicker);

/** @ngInject */
function selectpicker() {
return {
restrict: 'A',
require: '?ngOptions',
priority: 1500, // make priority bigger than ngOptions and ngRepeat
link: {
pre: function(scope, elem, attrs) {
elem.append('<option data-hidden="true" disabled value="">' + (attrs.title || 'Select something') + '</option>')
},
post: function(scope, elem, attrs) {
function refresh() {
elem.selectpicker('refresh');
}

if (attrs.ngModel) {
scope.$watch(attrs.ngModel, refresh);
}

if (attrs.ngDisabled) {
scope.$watch(attrs.ngDisabled, refresh);
}

elem.selectpicker({
dropupAuto: false,
hideDisabled: true
});
}
}
};
}


I need to run refresh() when my ng-options change (with filter)

Answer

You can create a model-watch to be used at second selector:

<select ng-model="vm.mySecondModel"
    model-watch="vm.myFirstModel"
    ng-options="hour.id as hour.label for hour in vm.hours | filter:vm.filterHours(vm.myFirstModel)" selectpicker>

and then, watch for this:

if (attrs.modelWatch) {
    scope.$watch(attrs.modelWatch, refresh);
}