Question

I'm creating a select element in my Angular template with the following markup:

<select name="noOfPeople" ng-model="noOfPeople" ng-options="value for value in [] | range:12">
    <option value="">No of people*</option>
</select>

I want some custom styling and functionality added to this select element, and for that I'm using the Chosen jQuery library.

To initialize the CHosen library on a select element I've written this directive:

directive('select', function() {
    return {
        restrict: 'E',
        link: function(scope, elm, attrs) {
            $(elm).chosen({disable_search: true});
        }
    }
})

This is working really well, and Chosen is now initialized on all of the <select> elements in my application. However this doesn't seem to work with using ng-options as the div's created by Chosen don't include any of the options generated by ng-options. If I look at the original <select> element in Chrome's developer tools though I can see the options are being generated.

My theory is that Chosen is being initialized on the <select> element before Angular has a chance to run ng-options and create the <option> elements in the DOM.

Is there a way I can defer the initialization of Chosen until Angular has finished its processing and added all of the <option> elements I want?

Was it helpful?

Solution

You can inject and use $timeout without a delay to put the action at the end of the browser event queue (after the rendering engine):

app.directive('select', function($timeout) {
  return {
    restrict: 'E',
    link: function(scope, elm, attrs) {
      $timeout(function() {
        $(elm).chosen({
          disable_search: true
        });
      });
    }
  };
});

Note that this case is assuming the data for ngOptions is available at initialization and not retrieved asynchronously.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top