简体   繁体   中英

Angularjs and the bootstrap-select plugin

I want to create an Angular directive to use the bootstrap-select plugin and specifically the option to use a data-subtext attribute on the <option> tag as shown here which would require something like this :

html markup

<select>
    <option data-subtext="Mustard's yellow" >Mustard</option>
    <option data-subtext="Ketchup's red">Ketchup</option>
    <option data-subtext="I don't know about Relish">Relish</option>
</select>

javascript

$('select').selectpicker({showSubtext:true});

I think ng-options is out of the question since I have to add the data-subtext to each <option> tag (correct me if I'm wrong).

What I have so far is this :

index.html

<select ng-model="idCourse" class="form-control input-sm" data-live-search="true" select-picker>
    <option ng-repeat="c in cources" value="{{c.id}}" data-subtext="{{c.name}}">{{c.code}}</option>
</select>

module.js

angular.module('myApp', [])

  .controller('ctrl',['$scope', function($scope){
    $scope.courses = [
      {id:1, code:'CS1607', name:'computer science beginner'},
      {id:2, code:'PH006', name:'Quantum physics'},
      {id:3, code:'CSB-9', name:'Machine Learning'}
      ];
  }])

  .directive('selectPicker', function(){
    return {
      restrict: 'A',
      link:function(scope, elem){
        elem.selectpicker({showSubtext:true});
      }
    };
});

The problem I'm having is that the select plugin is called before angular could fill it with the data, I've created a plunker for the code. Thanks for the help.

EDIT

As mer10z_tech suggested, using $timeout solved the problem :

//omitted...
.directive('selectPicker', ['$timeout', function($timeout){
    return {
      restrict: 'A',
      link:function(scope, elem){
        $timeout(function() {
          elem.selectpicker({showSubtext:true});
        }, 0);
      }
    };
}]);

I would bind your selectPicker plugin after angular compiles the view. Her is how to do that

function MyCtrl($scope) {
    angular.element(document).ready(function () {
        $('select').selectpicker({showSubtext:true});
    });
}

It is equivalent of $(document).ready()

I know the post was made long time ago but I hope this solution will be helpful for others.

I got another solution to the issue related.

What I did was first load my data from back-end using angularjs and inside the .success after my validation I wrote the following code:

angular.element(document).ready(function () {
    $('select').selectpicker("destroy"); 
    $('select').selectpicker("render"); 
});

I tried to do it without angular.element(document).ready(function (){}) but nothing happend. I suppose the plugin's methods only works inside that function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM