使用AngularJS时,Selectpicker不会填充

时间:2017-10-24 00:43:13

标签: angularjs bootstrap-selectpicker

我试图填写选择选项(selectpicker),但没有成功。我的能力正确填充,但在我的HTML中从未出现过选项。

有人可以帮我处理selectpicker吗?

JS

(() => {
  angular
    .module('talent')
    .controller('FunctionalityCreateCtrl', Create);

  function Create($timeout, GatewayService) {
    const vm = this;
    vm.form = {};
    vm.competencesArray = [];

    getCompetences();

    function getCompetences() {
      GatewayService.get('/competences')
        .then((data) => {
          vm.competencesArray = data._embedded;
        })
        .catch(() => {
          console.log('nope');
        });
    }
  }
})();

HTML

<select 
   class="selectpicker"                     
   data-style="select-with-transition" 
   title="Select a value" 
   data-size="7" 
   ng-model="functionality.form.comp"
   ng-options="s.name for s in functionality.competencesArray">
 <option value=""> Select</option>                      
 <select>

2 个答案:

答案 0 :(得分:2)

完成ajax请求后,您应该刷新选择选择器。来自文档:

  

要以编程方式使用JavaScript更新选择,请先进行操作   select,然后使用refresh方法更新UI以匹配   新国家。删除或添加选项时,或者何时,这是必需的   通过JavaScript禁用/启用选择。

完成ajax请求后,需要刷新选择,并将其放在$ timeout中以进行角度重新渲染dom。这是一个例子:

function getCompetences() {
  GatewayService.get('/competences')
    .then((data) => {
      vm.competencesArray = data._embedded;
    $timeout(function(){
     $('.selectpicker').selectpicker('refresh'); //put it in timeout for run digest cycle
    },1)
    })
    .catch(() => {
      console.log('nope');
    });
}

希望有所帮助

答案 1 :(得分:0)

您还没有发布代码的完整上下文,所以我假设您已经定义了角度模块&#34; talent&#34;并且该元素在FunctionalityCreateCtrl的范围内。我已经使用ng-app和ng-controller属性将您的示例HTML包装在div中,这样就可以使用该示例了。

我在您发布的代码示例中看到的第一个错误是元素未正确关闭。 close标签缺少正斜杠:</select>

另一个错误是你将select元素的模型设置为form.comp但是form.comp似乎没有设置为任何东西。我在下面的代码示例中添加了它。

另请注意,我已在ng-options表达式中添加了一个id ng-options="s.id as s.name for s in functionality.competencesArray">这样我就可以将模型(form.comp)设置为我知道的值。您的数据可能不同。

使用html片段:

<div ng-app="talent" ng-controller="FunctionalityCreateCtrl as functionality">
  <select 
     class="selectpicker"                     
     data-style="select-with-transition" 
     title="Select a value" 
     data-size="7" 
     ng-model="functionality.form.comp"
     ng-options="s.id as s.name for s in functionality.competencesArray">
   <option value=""> Select</option>                      
   </select>
</div>

使用Javascript代码段(我已经添加了人才模块定义并删除了api调用以便示例正常运行):

(() => {
  angular.module('talent', []);

  angular
    .module('talent')
    .controller('FunctionalityCreateCtrl', Create);

  function Create() {
    const vm = this;
    vm.form = {};
    vm.competencesArray = [];

    getCompetences();

    function getCompetences() {
      vm.competencesArray = [
        { id: 1, name: 'test 1' },
        { id: 2, name: 'test 2' },
        { id: 3, name: 'test 3' }
      ];

      vm.form.comp = 1;
    }
  }
})();

这是一个使用您的示例代码的工作JSFiddle:https://jsfiddle.net/g8r9ajtL/