2014-11-23 45 views
0

我从perl脚本获取json respose。这是响应看起来像这样。如何在Angularjs中使用JSON数据分配/填充HTML选择

alert (respose) // ouput - object 
var json = JSON.stringify(response); 
alert (json); 

output: 

{ 
    "brands": [ 
     { 
      "brand_image_path": "/images/brands/aakash.png", 
      "brand_name": "Aakash", 
      "brand_id": "74" 
     }, 
     { 
      "brand_image_path": "/images/brands/aashirvaad.png", 
      "brand_name": "Aashirvaad", 
      "brand_id": "51" 
     }, 
     { 
      "brand_image_path": "/images/brands/yardley.png", 
      "brand_name": "Yardley", 
      "brand_id": "25" 
     } 
    ] 
} 

在得到脚本的响应后,我将它赋值给$ scope这样。

$scope.brandlist = response; 

这两个警告给我正确的价值。

alert ($scope.brandlist.brands[1].brand_name); 
alert ($scope.brandlist.brands[2].brand_id); 

我想如何用这些数据填充我的HTML页面中的选择列表。我使用相同的代码。

<select ID="select-add-new-product-brand-name" ng-model="selectedItem" ng-options="brand.brand_id as brand.brand_name for brand in brandlist"></select> 

但它没有为我找到任何数据。这是什么错?

回答

0

这里有几个问题。

首先,您正在循环一个对象(“品牌”)而不是您想要的对象数组。当你得到你的ajax响应对象时,将品牌列表设置为控制器中的对象数组。

app.controller('MainCtrl', function($scope, $http) { 
    $http.get('some/api/').then(function(result){ 
    $scope.brandList = result.brands; 
    }); 

其次,您应该在控制器中设置默认选择选项。因为你想通过你的对象的BRAND_NAME属性引用brand_id,您应该设置默认选项,如下所示:

app.controller('MainCtrl', function($scope, $http) { 
    $http.get('some/api/').then(function(result){ 
    $scope.brandList = result.brands; 
    $scope.selectedItem = $scope.brandList[1].brand_id; // set the second item as default 
    }); 

现在你应该看到在你的HTML渲染一切。

看到这个猎物http://plnkr.co/edit/cgxhhe8Qh2UfCUAxSDio?p=preview