【问题标题】:Angularjs and the bootstrap-select pluginAngularjs 和 bootstrap-select 插件
【发布时间】: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 添加到每个&lt;option&gt; 标签(如果我错了,请纠正我)。

到目前为止,我所拥有的是:

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


【解决方案1】:

我会在 Angular 编译视图后绑定你的 selectPicker 插件。她是怎么做到的

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

相当于$(document).ready()

【讨论】:

  • 不幸的是,它没有工作,选择列表仍然是空的。
【解决方案2】:

我知道该帖子是很久以前发布的,但我希望此解决方案对其他人有所帮助。

我有另一个解决相关问题的方法。

我所做的是首先使用 angularjs 从后端加载我的数据,并在验证后在.success 中写入以下代码:

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

我试图在没有angular.element(document).ready(function (){}) 的情况下这样做,但什么也没发生。我想插件的方法只适用于该函数。

【讨论】:

    猜你喜欢
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    • 2019-02-08
    • 2014-03-30
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多