如何使用ng模型绑定动态复选框值
How to bind dynamic Check boxes value using ng-model?
我想用与使用"name"属性类似的方式,使用"ng model"将动态复选框的值(而不是布尔值true和false)以数组的形式放置。这个数组现在被放入一个JSON对象中。
<td>
<span ng-repeat="operation in operations_publish">
<input type="checkbox" name="operations" ng-model="operations" value="{{operation}}"/>
{{operation}}
</span>
</td>
以下是我发布JSON对象的函数:
$scope.send = function() {
console.log("test");
var dataObj = {
"operationType" : $scope.operationType,
"conceptModelID" : $scope.conceptID,
"requestor" : $scope.requestor,
"status" : "new",
"requestDateTime" : null,
"lastExecutedDateTime" : null,
"completedDateTime" : null,
"instructions" : $scope.operations
};
console.log(dataObj);
console.log(dataObj.instructions);
var response = $http.post('PostService', dataObj);
response.success(function(data, status, headers, config) {
$scope.responseData = data;
});
response.error(function(data, status, headers, config) {
alert("Exception details: " + JSON.stringify({
data : data
}));
});
但是当我运行代码时,"dataObj.instructions"是未定义的。请说明这是否是正确的做法,以及我在这里缺少什么。
您必须将每个输入绑定到不同的值。目前,它们都通过ng-model="operations"
绑定到作用域中的字段operations
。
我建议您在控制器中创建一个数组operations
,如下所示:
$scope.operations = new Array($scope.operations_publish.length);
然后,您可以将复选框绑定到此数组中的相应索引:
<span ng-repeat="operation in operations_publish">
<input type="checkbox"
name="operations"
ng-model="operations[$index]"
value="{{operation}}"/>
{{operation}}
</span>
这将为您提供一个在所有已检查索引处具有true
的数组。如果您想要将所选值作为数组中的字符串,您可以这样收集它们:
function getSelected() {
return $scope.operations_publish.filter(function (x,i) {
return $scope.operations[i]
});
}
检查这个小提琴的完整代码。
你试过了吗?
<input type="checkbox" ng-model="cbValues[$index]"
ng-repeat="value in cbValues track by $index" />
适用于我:http://plnkr.co/edit/s0rZiMeL4NvpFZ3C9CIL?p=preview
根据上面列出的示例,您已经将ng-model
绑定到表达式operations
,但需要将其绑定到单个迭代器operation
(来自)ng-repeat="operation in operations_publish"
。
然后,您可以在dataLog对象中设置该数据:
var dataObj = {
"operationType" : $scope.operationType,
"conceptModelID" : $scope.conceptID,
"requestor" : $scope.requestor,
"status" : "new",
"requestDateTime" : null,
"lastExecutedDateTime" : null,
"completedDateTime" : null,
"instructions" : $scope.operations_publish
};
默认情况下,角度数据绑定是多向的,因此:
operations_publish
=>通过迭代器operation
绑定到行operation
=>通过ng-model
绑定到复选框值- 当复选框的值更改时,您将更改它绑定到的变量,以及该变量从中迭代的集合
相关文章:
- 基于所选下拉列表值创建动态复选框
- 动态复选框onchange&javascript
- 从动态复选框的父级中提取类名
- LiveCycle:在动态复选框中循环
- 基于动态复选框过滤数据 角度 JS中的类别
- 使用 jQuery 获取动态复选框值
- 通过在 DOJO 中迭代 JSONArray 来创建动态复选框
- 动态复选框创建以在单击时运行函数
- 动态复选框被重置
- 通过javascript访问(checkall,uncheck,middlestate)到asp表中的动态复选框
- 添加为动态复选框选中的属性
- 动态复选框列表的JavaScript验证
- 如何使用ng模型绑定动态复选框值
- 将鼠标悬停效果添加到动态复选框
- 动态复选框隐藏动态输入框
- 如何使用AJAX基于数据库中的值创建动态复选框
- 从下拉菜单中创建动态复选框
- 动态复选框列表不起作用
- 通过动态字段中的动态复选框复制地址
- 动态复选框,单选,checkboxgroups, radiogroups extjs