我想使用'ng-model'以类似于使用'name'属性的方式将动态复选框的值(不是布尔值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”是未定义的。请建议这样做是否正确,以及我在这里缺少什么。
最佳答案
您必须将每个输入绑定到一个不同的值。当前,所有它们都通过operations
绑定到范围中的字段ng-model="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]
});
}
检查this fiddle以获取完整的代码。
关于javascript - 如何使用ng-model绑定(bind)动态复选框值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34006596/