问题描述
我想以与使用'name'属性相似的方式使用'ng-model'以数组的形式放置动态复选框的值(不是布尔值true和false)。此数组现在放入JSON对象中。
I want to put the values of dynamic checkboxes (not boolean true and false) in the form of array using 'ng-model' in a similar way as is done using 'name' attribute. This array is now put into a JSON object.
<td>
<span ng-repeat="operation in operations_publish">
<input type="checkbox" name="operations" ng-model="operations" value="{{operation}}"/>
{{operation}}
</span>
</td>
以下是我发布JSON对象的函数:
Following is my function to post the JSON object:
$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'是未定义的。请说明这是否是正确的做法以及我在这里缺少的。
But 'dataObj.instructions' is undefined when I run the code. Please suggest whether it is the right way of doing it and what am I missing here.
推荐答案
您必须将每个输入绑定到不同的值。目前所有这些都通过 ng-model =operations
绑定到范围操作
字段。
You have to bind each input to a different value. Currently all of them are bound to the field operations
in the scope via ng-model="operations"
.
我建议您在控制器中创建一个数组 operations
,如下所示:
I suggest you create an array operations
in your controller like this:
$scope.operations = new Array($scope.operations_publish.length);
然后你可以将复选框绑定到这个数组中相应的索引:
Then you can bind the checkboxes to the respective index in this array:
<span ng-repeat="operation in operations_publish">
<input type="checkbox"
name="operations"
ng-model="operations[$index]"
value="{{operation}}"/>
{{operation}}
</span>
这将为您提供一个 true的数组
在所有检查的索引。如果您希望将所选值作为数组中的字符串,则可以像这样收集它们:
This will give you an array with true
at all checked indexes. If you then want the selected values as strings in an array, you can collect them like this:
function getSelected() {
return $scope.operations_publish.filter(function (x,i) {
return $scope.operations[i]
});
}
检查代表完整的代码。
这篇关于如何使用ng-model绑定动态复选框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!