Search code examples
javascriptangularjsng-options

Angular - Binding the following data via ng-options for a select field


Given the following code:

http://jsfiddle.net/KN9xx/1102/

Suppose I received an ajax call with the following data I pass to a scope variable:

$scope.people_model = {  
   "people":[  
      {  
         "id":"1",
         "name":"Jon"
      },
      {  
         "id":"2",
         "name":"Adam"
      }
   ]
};

How would I work with the select box to iterate over the 'people' via ng-options?

<select 
  ng-options="p.name for name in people_model"
  ng-model="people_model">
</select>

Solution

  • Change your select as ,

     <select ng-model="currentSelected" ng-options="selection.id as selection.name for selection in people_model.people"></select>
    

    You need to access the array people inside the object people_model

    DEMO

    var app = angular.module('myapp', []);
    
    app.controller("FirstCtrl", ["$scope",
      function($scope) {
        $scope.currentSelected = "1";
        $scope.people_model = {
          "people": [{
            "id": "1",
            "name": "Jon"
          }, {
            "id": "2",
            "name": "Adam"
          }]
        };
    
      }
    ]);
    <!DOCTYPE html>
    <html ng-app="myapp">
    
    <head>
      <title>To Do List</title>
      <link href="skeleton.css" rel="stylesheet" />
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
      <script src="MainViewController.js"></script>
    </head>
    
    
    <body ng-controller="FirstCtrl">
      <select ng-model="currentSelected" ng-options="selection.id as selection.name for selection in people_model.people"></select>
    </body>
    
    </html>