Angular UI select : Fetch data from remote service

Syed picture Syed · Sep 26, 2014 · Viewed 40.9k times · Source

I am using angular UI select.

https://github.com/angular-ui/ui-select

I looked around the demo's available at this plunkr

I want to fetch data from a remote service. Every time user types something into the text field. I want to fetch data from remote service with results filtered based on input value.

I have written a web service and web service is working fine.

How can I use angular ui select to fetch data from remote service ?

Currently I am following simple example from demo

  <ui-select multiple ng-model="multipleDemo.colors" theme="select2" ng-disabled="disabled" style="width: 300px;">
    <ui-select-match placeholder="Select colors...">{{$item}}</ui-select-match>
    <ui-select-choices repeat="color in availableColors | filter:$select.search">
      {{color}}
    </ui-select-choices>
  </ui-select>

availableColors is a predefined array. I don't want to define data array beforehand.

I have been looking around the Internet for any possible documentation or tutorial but not able to find anything useful.

Answer

ababashka picture ababashka · Sep 26, 2014

In your example, at first you must initialize your availableColors as an empty array:

$scope.availableColors = [];

Then, you can write your simple service with $http:

$http.get('data.json').then(
  function (response) {
    $scope.availableColors = response.data;
    $scope.multipleDemo.colors = ['Blue','Red'];
  },
  function (response) {
    console.log('ERROR!!!');
  }
);

So, now you can use this code without pre-defining your availableColors by some values.

Demo: http://plnkr.co/edit/BcJOezOABxSuc2fa5lRy?p=preview

In this example I added file data.json which contains an array of colors.

It's a very simple example, but I hope that it will help you. Changes start from line 118 in file demo.js.

Edit

If you want to dynamically update your list of choices - you can use the attributes refresh and refresh-delay of the ui-select-choices directive.

The first attribute, as you can guess, gets function like

refresh="funcAsync($select.search)"

which will be called every time you type anything. And you can use the second attribute as

refresh-delay="0"

As you can guess it is used for set delay of calling refresh function in milliseconds. By default this value is set to 1000.

Demo: http://plnkr.co/edit/BcJOezOABxSuc2fa5lRy?p=preview

I updated my plunk, so I decided not to write own backend functions. That's why you can check it works by simply typing red in the first ui-select field - values will be got from another .json file - data1.json.

Hope, it will help you.