如何获取选中的复选框值并将其数组变量存储在angularjs中?

s1l*_*m8u 3 javascript checkbox angularjs

我已经创建了数组列表并将其列出为多个复选框。从那里,如果我选择我存储到数组变量,如果我取消选中它需要从数组中删除。我试过了,但是取消选中的值没有从数组变量中删除。

这是我下面的代码和jsfiddle

的HTML

<div ng-app="myApp" ng-controller="MyCtrl">
    <lable ng-repeat="list in lists">
    <input type="checkbox" name="chk[]" ng-model="lst" value="{{list.vl}}" ng-change="change()">
    {{list.vl}} <br>
    </lable>
</div>
Run Code Online (Sandbox Code Playgroud)

脚本

var myApp = angular.module('myApp', []);

myApp.controller('MyCtrl', function($scope){
    $scope.lists = [
        {'vl' : 1},
        {'vl' : 2},
        {'vl' : 3},
        {'vl' : 4},
        {'vl' : 5},
    ];

    $scope.lst = [];
    $scope.change = function(){
        $scope.lst.push('2');
        console.log($scope.lst);
    };
});
Run Code Online (Sandbox Code Playgroud)

han*_*aad 5

您可以通过传递数据ngChange来决定是否要推送或拼接。

的HTML

<lable ng-repeat="list in lists">
    <input type="checkbox" ng-model="active" ng-change="change(list, active)" >
</lable>
Run Code Online (Sandbox Code Playgroud)

脚本

$scope.change = function(list, active){
    if (active)
        $scope.lst.push(list);
    else
        $scope.lst.splice($scope.lst.indexOf(list), 1);
};
Run Code Online (Sandbox Code Playgroud)

请注意,每个项目的当前值都存储在active隔离范围内的变量中。如果您需要模型中的值,请像这样进行绑定:

<lable ng-repeat="list in lists">
    <input type="checkbox" ng-model="list.active" ng-change="change(list, active)" >
</lable>
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/ruzw4Lfb/8/