【问题标题】:How to update ng-model dynamically in ng-repeat?如何在 ng-repeat 中动态更新 ng-model?
【发布时间】:2013-07-10 23:07:29
【问题描述】:

我的角度页面中的动态 ng-model 值存在一些问题。这是我的示例 JSON。

mytabs = [
    {
        name : "tab1",
        values : [
            {value:"value1"},
            {value:"value2"},
            {value:"value3"},
            {value:"value4"}
        ]
    },
    {
        name : "tab2",
        values : [
            {value:"value1"},
            {value:"value2"},
            {value:"value3"},
            {value:"value4"}
        ]
    }
]

我想从这个 josn 中做的是,在我的页面中创建一个视图,这样,它将包含 tab1tab2 作为页面标题,并将相应的 value 作为 checkbox。用户将具有选择他的选项的选择性。在提交时,我想获得他选择的选项。我想知道在我的控制器中选择了value1,value3 (frome tab1)value1,value2(from tab2) 之类的东西。我该怎么做?
这是我的示例方法。

<div ng-repeat="tab in mytabs">
  <h1>{{tab.name}}</h1>
    <div ng-repeat="val in tab.values">
        <input type="checkbox" ng-model="val.value"/>
    </div>
</div>
<input type="button" value="submit" ng-click="checkValues(val)"

请帮帮我,
谢谢

【问题讨论】:

  • 您的 json 无效。名称:tab1 --> 名称:“tab1”
  • 抱歉,只是输入错误。无论如何,我身边都有有效的 json

标签: angularjs dynamic-data angularjs-ng-repeat ng-repeat


【解决方案1】:

你应该稍微修改你的代码,你应该在对象中添加一个选中的属性并将复选框绑定到该模型。

请使用下面的想法或代码更接近你想要的东西

 <div ng-repeat="tab in mytabs">
  <h1>{{tab.name}}</h1>
    <div ng-repeat="val in tab.values">
        <input type="checkbox" ng-model="val.checked"/>
    </div>
</div>
<input type="button" ng-click="checkValues()" value="checkitems" />

    <script>
        var app = angular.module('plunker', []);

        app.controller('MainCtrl', function ($scope,$filter) {
            $scope.mytabs = [
                {
                    name: "tab1",
                    values: [
                        { value: "value1",checked:false },
                        { value: "value2", checked: false },
                        { value: "value3", checked: false },
                        { value: "value4", checked: false }
                    ]
                },
                {
                    name: "tab2",
                    values: [
                       { value: "value1", checked: false },
                       { value: "value2", checked: false },
                       { value: "value3", checked: false },
                       { value: "value4", checked: false }
                   ]
                }
            ];

            $scope.checkValues = function () {
                angular.forEach($scope.mytabs, function (value, index) {
                    var selectedItems = $filter('filter')(value.values, { checked: true });
                    angular.forEach(selectedItems, function (value, index) {
                        alert(value.value);
                    });

                });
            };
        });

【讨论】:

  • 谢谢 Ajay beniwal,这太棒了。非常感谢。你把我从延迟天的循环中救了出来。
最近更新 更多