Search code examples
angularjstwitter-bootstrapangularjs-directiveangularjs-scopebootstrap-select

Bootstrap-Select Plugin with Angular JS and ajax data not working


http://plnkr.co/edit/1ATuPILnevk6gCvYRvee?p=preview

angular.module('emfModule')
  .directive('selectpicker', function ($timeout) {
      return {
          restrict: 'C',
          link: function (scope, element, attrs) {

              var $el = $(element);
              $timeout(function () {

                  $el.selectpicker({
                      style: 'btn-default',
                      size: false
                  });


              });


          }
      };
  });     

Hi I am trying to load data via ajax into a dropdown in an angular app. The data is coming through and i am able to populate the control but when I try to use the bootstrap-select plugin, it fails. I tried to wrap it up using an angular directive but didnt help. The Plunk above describes my use case. Can someone let me know where I am going wrong. Thank You


Solution

  • http://plnkr.co/edit/7YR5R4aTFWDelwFDz7jV?p=preview

    I've changed you selectpicker directive. It's waiting until data for options loads + a bit more time for angular so it could rebuild select. And only after that I call select-bootstrap plugin. And also directive restrict changed from C to A.

    angular.module('emfModule')
    .directive('selectpicker', function($timeout) {
      return {
        restrict: 'A',
        link: function(scope, element, attrs) {
    
          var $el = $(element);
    
          var unsubscribe = scope.$watch(attrs.selectpickerOptions, function(opts) {
            if (opts) {
              $timeout(function() {
                $el.selectpicker({
                  style: 'btn-default',
                  size: false
                });
                unsubscribe();
              });
            }
          })
    
        }
      };
    });
    

    And here's you element. I've removed class selectpicker because I don't want select-bootstrap call himself.

    <select title="Select" ng-options="c.login  for c in Users" ng-model="login" name="login" selectpicker="" selectpicker-options="Users" class="form-control input-sm">
       <option value="">-- choose user --</option>
    </select>