2017-04-04 30 views
0

如果你看下面的代碼,我該如何動態地區分每個選擇下拉菜單?在ng-repeat中動態迭代的選項值

如果選中,所有下拉菜單都顯示相同的值。

要求是我想根據響應結構動態地從1到10選項值(在數組中聲明)中顯示3個下拉列表 - 在這種情況下,有三個產品,因此需要顯示三個動態下拉列表。

實現此目的的有效方法是什麼?

HTML

<div ng-controller="MyCtrl"> 
     <div ng-repeat="product in colors.item"> 
     <div ng-if="quan!=true"> 
      <select ng-model="selectedItems.val" ng-init="selectedItems.val = selectedItems.val + ''"> 
       <option ng-repeat="value in arr | limitTo:quantity">{{value}}</option> 
     </select> 
    </div> 
    </div> 
<div> 
    <a href="#" ng-click="submit(selectedItems.val)">Submit</a> 
</div> 
</div> 

JS

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

//myApp.directive('myDirective', function() {}); 
//myApp.factory('myService', function() {}); 

myApp.controller('MyCtrl', function MyCtrl($scope) { 

$scope.colors = {"category": "students" 
"item":[ 
    { 
    "product":{ 
      "name":"abc", 
      "age": "24" 
    } 
    "boo": true 
    }, 
    { 
    "product":{ 
      "name":"def", 
      "age": "44" 
    } 
    }, 
    { 
    "product":{ 
      "name":"ghi", 
      "age": "22" 
    } 
    } 
    ]}; 
$scope.quan = false; 
$scope.arr = []; 
for(var a=1; a<=10; a++) { 
    $scope.arr.push(a); 
} 
$scope.selectedItems = {val : $scope.arr[0]}; 
$scope.quantity = 10; 
$scope.submit = function(av){ 
alert(av); 
} 

}); 

JSFIDDLE CODE

+0

爲什麼不使用'NG-options'? – tanmay

+0

試過這個......當加載這個 –

+0

時出現了注射器錯誤什麼是預期行爲? – tanmay

回答

1

的問題是你的selectedItems一個,你必須colorsarray

你可以有selectedItemscolors這樣的:

$scope.colors.map(function(obj) { 
    return obj.selectedItems = { 
    val: $scope.arr[0] 
    } 
}) 

現在,改變你的<select>這樣的:

<select ng-model="product.selectedItems.val" ng-init="product.selectedItems.val = product.selectedItems.val + ''"> 
    <option ng-repeat="value in arr | limitTo:quantity">{{value}}  
    </option> 
</select> 

而且,submit如:

$scope.submit = function() { 
    $scope.colors.forEach(function(obj) { 
    console.log(obj.selectedItems.val) 
    }) 
} 

working fiddle

或者,你可以先ng-repeat內使用的$indexselectedItems單獨比colors

0

提供唯一的ID來選擇像id元素= {{$索引+ 1}}來區分bewteen所有選擇下拉菜單。