【发布时间】:2014-05-27 12:57:37
【问题描述】:
我想创建一个 Angular 指令来使用 bootstrap-select 插件,特别是在 <option> 标签 as shown here 上使用 data-subtext 属性的选项,这需要这样的东西:
html 标记
<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});
我认为ng-options 是不可能的,因为我必须将data-subtext 添加到每个<option> 标签(如果我错了,请纠正我)。
到目前为止,我所拥有的是:
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});
}
};
});
我遇到的问题是在 angular 可以用数据填充它之前调用了 select 插件,我为代码创建了一个 plunker。感谢您的帮助。
编辑
正如 mer10z_tech 建议的那样,使用 $timeout 解决了问题:
//omitted...
.directive('selectPicker', ['$timeout', function($timeout){
return {
restrict: 'A',
link:function(scope, elem){
$timeout(function() {
elem.selectpicker({showSubtext:true});
}, 0);
}
};
}]);
【问题讨论】:
-
您需要在指令中嵌入子元素。检查嵌入文档。
-
我将
transclude:true添加到我的指令中,仍然没有运气。 -
简单地添加 transclude:true 当然不会起作用,你必须处理被嵌入的元素,正如我所说的检查 transclude docs/tutorials。
-
在您的指令中,您可以将 elem.selectpicker 调用包装在超时函数中:
$timeout(function() {elem.selectpicker({showSubtext:true});}, 0);plnkr.co/edit/y60KQd -
@snajahi,您共享的代码 sn-p 正在工作,可能您应该增加超时时间。我已经为 ajax 调用编辑了你的,它可以在plnkr.co/edit/gk8N3MCzBxusvPwAPbyi?p=preview 获得,希望它对你有用:)
标签: jquery angularjs twitter-bootstrap angularjs-directive