我的 Angular 页面中的动态 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 做的是,在我的页面中创建一个 View ,它将包含 tab1
和 tab2
作为页面标题和相应的 value
作为 checkbox
。用户将有选择权来选择他的选项。提交时,我想获得他选择的选项。我想知道在我的 Controller 中选择了 value1,value3 (from 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)"
请帮帮我,
谢谢
最佳答案
你应该稍微修改你的代码,你应该在对象中添加一个选中的属性并将复选框绑定(bind)到该模型。
请使用下面的想法或代码更接近地得到你想要的东西
<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);
});
});
};
});
关于angularjs - 如何在 ng-repeat 中动态更新 ng-model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17614361/