2015-12-21 52 views
0

我想填充选择使用ng选项从webapi获取数据。使用angularJS绑定从api选择

基本上,我的WebAPI返回以下JSON:

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

,我需要生成显示名称属性中选择选项,而是用id作为值。

问题是我无法使用ng-options显示我的选项。这里就是我想:

<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

我希望这可以帮助你

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>

+0

差不多,但它并没有显示ID作为选项的值 –

+0

我认为你是错的,它会返回你的ID值!只需更改您的选择选项,您将看到id值 – Maher