SiberianGuy
SiberianGuy

Reputation: 25312

Execute code when ng-options is done

I have a select populated by ng-options:

<select id="personId" name="personId" class="selectpicker" 
        ng-model="person" ng-options="person.Surname for person in persons track by person.Id">
    <option value="">Introduce yourself...</option>
</select>

But what I need to display is not a select itself but a bootstrap-select (a plugin that builds div-based dropdownlist) based on it. So I need to call $('.selectpicker').selectpicker('refresh') when select items are updated. Is there any angularjs extension point where I can do that?

Upvotes: 1

Views: 1729

Answers (2)

boindiil
boindiil

Reputation: 5865

I have created the following plunkr with a working example.

myApp.directive("myselect", function($parse) {
  return {
    restrict: 'A',
    require: 'select',
    link: function(scope, element, attrs) {
      var ngModel = $parse(attrs.ngModel);

      $(element).selectmenu({
        "change": function(event, ui) {
          scope.$apply(function(scope) {
            // Change binded variable
            ngModel.assign(scope, $(element).val());
          });
        },
        "width": 200
      });

      var selectSource = jQuery.trim(attrs.ngOptions.split('|')[0]).split(' ').pop();
      var scopeCollection = $parse(selectSource);

      scope.$watchCollection(scopeCollection, function(newVal) {
        $(element).selectmenu('refresh');
      });
    }
  };
});

I have realized it with the help of the following resources:

http://www.grobmeier.de/angular-js-binding-to-jquery-ui-datepicker-example-07092012.html#.VAbLDfl_t1A

https://groups.google.com/forum/#!topic/angular/S-a_SLp3MyM

Upvotes: 1

rcijvat
rcijvat

Reputation: 182

You could achieve that by 'watching' the persons array. So in your controller, you could add the following code:

$scope.$watch('persons', function(newValue, oldValue) {
   if(!newValue || newValue === oldValue) return;

   //At this point, newValue contains the new value of your persons array
   $('.selectpicker').selectpicker('refresh');
});

The refresh of the selectpicker will then be executed each time the content of the persons array changes (including when it is first initialized)

Hope this helps.

Upvotes: 1

Related Questions