gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:32:37 24 4
gpt4 key购买 nike

我已经创建了数组列表并将其列为多个复选框。如果我选择我存储到数组变量中,如果我取消选中它需要从数组中删除。我试过这适用于但未选中值未从数组变量中删除。

下面是我的代码和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>

脚本

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);
};
});

最佳答案

你可以在ngChange中传递数据,你需要决定是推送还是拼接。

HTML

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

脚本

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

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

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

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

关于javascript - 如何获取选中的复选框值并将其存储在angularjs中的数组变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31185554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com