0

I'm trying to populate a Select getting data from a webapi using ng-options.

Basically, my webapi returns the following JSON:

{
   "items":[
      {
         "name":"X",
         "id":1
      },
      {
         "name":"Y",
         "id":2
      }
   ]
}

And I Need to generate options in a select displaying the name property, but with the id as value.

The problem is that I can't display my options using ng-options. Here's what I'm trying:

<html ng-app='app'>
<head>
    <title>angular</title>
</head>
<body ng-controller='DemoCtrl'>
    <select ng-model="selectedTestAccount" ng-options="option.name for option in testAccounts">
        <option value="">Select Account</option>
    </select>
    <script src='https://code.angularjs.org/1.5.0-rc.0/angular.min.js'></script>
    <script>
        angular.module('app', []).controller('DemoCtrl', function ($scope, $http) {
            $scope.selectedTestAccount = null;
            $scope.testAccounts = [];

            $http({
                method: 'GET',
                url: '/api/values',
                data: {}
            }).success(function (result) {
                console.log(result);

                $scope.testAccounts = JSON.parse(result.items);
            });
        });
    </script>
</body>
</html>

1 Answer 1

1

I hope this helps you

angular.module("app", []);
        angular.module("app").controller("ctrl", function($scope) {

          $scope.testAccounts = [];

            var youJson = [
                { "items": [{ "name": "X", "id": "your value for X" }, { "name": "Y", "id": "your value for Y" }] },
                { "items": [{ "name": "A", "id": "your value for A" }, { "name": "B", "id": "your value for B" }] }
            ];

          angular.forEach(youJson, function(items) {
            angular.forEach(items.items, function(item) {
              $scope.testAccounts.push(item);
            });
          });

          console.log($scope.testAccounts);
        });
<!doctype html>
<html ng-app="app" ng-controller="ctrl">

<head>
</head>

<body>
  <select ng-model="mySelect" ng-options="item.id as item.name for item in testAccounts"></select>
  {{mySelect}}
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-rc.0/angular.js"></script>
</body>

</html>

Sign up to request clarification or add additional context in comments.

2 Comments

Almost, it didn't display the id as options's value
I think you are wrong, it return exactly your id value!! just change your select option you will see the id value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.