How can I fill select2 data dynamically using angular

My point is that I want to use the createSearchChoice function of the Select2 widget. So I found that I need to use an html input element instead of a select element, so I cannot use ng-repeat to populate the select2 widget. I found there was a "data" option and was able to fill the select2 widget with static data, but not when I tried to execute it dynamically.

What works:

HTML: <input class='select2' ui-select2='sel2props' type='hidden'>

in the controller:

$scope.sel2props = {
    createSearchChoice: ...

  data: [ 
    { id: 0, text: 'yabba' }
    etc
  ]
};

      

But if I try to set the data to a variable that I can set to whatever the database feeds me, the widget doesn't populate.

data: $scope.data;

function to retrieve data {
    $scope.data = retrieved data;
}

      

the retrieved data exactly matches the one specified.

If I set a button to add data key, it works:

$scope.appenddata = function () {
  $scope.data.push({id:1, text: 'anot'});
};

      

So I think this is a timing issue and I am trying to use $ digest and $ apply but they don't work in controllers. I tried to create a directive and can actually do simple widgets, but not select2, so I was hoping not to go that route, well, that is, I went that route and drowned. If anyone could help it would be great.

+3


source to share


3 answers


The solution is straightforward. Just push the items to the select2 dataset, not referencing another array.



+5


source


function (result) {
  $scope.lookupOptions.data.length = 0; // remove old items
  angular.extend($scope.lookupOptions.data, result.data); // add new items                  
}

      



+1


source


A trick I recently used is to use the Select2 option query

to pass the latest data on demand.

I put together an example wrapped in a custom directive. See Plunk .

-1


source







All Articles