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);
}
};
}]);