serge
serge

Reputation: 15239

Use $http.get to obtain value of a select

AngularJs(1). I have 2 HTML selects. Each select uses the values from an ajax call ($http.get)

First:

<option ng-repeat="lab in getLabels('A')" value="{{lab}}">{{lab}}</option>

Second:

<option ng-repeat="lab in getLabels('X')" value="{{lab}}">{{lab}}</option>

the problem is that because of ajax, getLabels returns a promise, and not a direct list. How to workaround this problem, knowing that I have to use a specific parameter for each of 2 selects?

Here is my test pen (where I simulate an ajax call with the "$q" service)

Upvotes: 0

Views: 164

Answers (1)

Drag13
Drag13

Reputation: 5998

Do not bind directly. Use a mediator: (UPDATED!) Smth like this

    var myApp = angular.module('myApp', []);

myApp.controller('CartController', ['$scope', function($scope) {

}]);

myApp.directive('initiator', function($q) {
  return {

    link: function($scope, $elem, $attr) {
      var param = $attr.param;
      var deferred = $q.defer();
      var promise = deferred.promise;
      $scope.list = {};

      var labels = [];
      if (param == "A") {
        labels.push("pervii");
        labels.push("first");
      } else if (param == "X") {
        labels.push("poslednii");
        labels.push("last");
        labels.push("dernier");
      } else {
        labels.push("middle");
        labels.push("srednii");
        labels.push("moyen");
      }

      deferred.resolve(labels);
      promise.then(function(data) {
        console.log(data);
        $scope.list[param] = data;
      });

    }
  }
});

<div ng-app="myApp">
  <div ng-controller="CartController">
    <select ng-model="label3" initiator param="A">
      <option ng-repeat="lab in list['A']" >{{lab}}</option>
    </select>
  </div>
</div>

Upvotes: 1

Related Questions