Search code examples
angularjsbootstrap-selectpicker

Selectpicker doesn't fill when using with AngularJS


I'm trying to fill a select options (selectpicker), but without success. My competenceArray is filled correctly, but in my HTML never appears the options.

Someone can help me with the 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>

Solution

  • You should refresh select picker after complete ajax request . From the docs :

    To programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.

    When complete ajax request , you need refresh select , and put it in $timeout for angular re-render dom . Here is example :

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

    Hope it help