选择选项值未在ng-repeat中动态迭代 [英] select option value not iterated dynamically in ng-repeat

查看:73
本文介绍了选择选项值未在ng-repeat中动态迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您看下面的代码,我该如何动态区分每个选择的下拉列表?

If you look at the below code, how do i differentiate each and every select dropdowns dynamically?

如果选中所有下拉列表,则显示相同的值.

All dropdowns are showing the same value if selected.

需求是我想根据响应结构从1到10个选项值(在数组中声明)动态显示3个下拉列表-在这种情况下,有3个产品,因此需要显示3个动态下拉列表.

Requirement is I wanted to show 3 dropdowns dynamically from 1 to 10 option value (declared in array) based on the response structure - in this case, there are three products, so three dynamic dropdowns needs to be displayed.

实现此目标的有效方法是什么?

what is the efficient way to achieve this?

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代码

推荐答案

问题是您的 selectedItems 一个,并且具有 colors 作为 数组 .

The problem is your selectedItems is one and you have colors as array.

您可以在 colors 中包含 selectedItems ,如下所示:

You can have selectedItems inside colors like this:

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

现在,像这样更改您的< select> :

Now, change your <select> like this:

<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>

然后,提交如下:

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

工作小提琴

或者,您可以在第一个 ng-repeat 中使用 $ index ,以使 selectedItems colors 分开>

Alternatively, you can make use of $index inside first ng-repeat to have selectedItems seperate than colors

这篇关于选择选项值未在ng-repeat中动态迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆