如何使用ng模型绑定动态复选框值

How to bind dynamic Check boxes value using ng-model?

本文关键字:动态 复选框 绑定 模型 何使用 ng      更新时间:2023-09-26

我想用与使用"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
};

默认情况下,角度数据绑定是多向的,因此:

  1. operations_publish=>通过迭代器operation绑定到行
  2. operation=>通过ng-model绑定到复选框值
  3. 当复选框的值更改时,您将更改它绑定到的变量,以及该变量从中迭代的集合