gpt4 book ai didi

javascript - 复选框无法与 ng-repeat、AngularJs 一起正常工作

转载 作者:行者123 更新时间:2023-12-03 07:01:59 24 4
gpt4 key购买 nike

我想使用 ng-repeat 制作多选复选框。如果我没有预先选择的复选框,它工作正常。但是当我预先选择了复选框时,它的行为就完全不寻常了。

<div ng-repeat="account in accounts">
<input ng-model="selectedAccounts[account.id]"
ng-checked="{{account.lastchecked}}" type="checkbox">
</div>

在 Controller 中我选择的 id 为:

$scope.selectedAccounts = [];
angular.forEach($scope.selectedAccounts, function(value, key) {
if(value == true) {
selectedIds.push(key);
}
});

这里的问题是我必须使用初始数组初始化 selectedAccounts 。如果我不这样做,那么它会给我不确定的。当我对某些帐户设置“lastchecked”为 true 时,它​​会根据 lastchecked 显示预先检查的值,但是当我尝试检索 $scope.selectedAccounts 时,它会给我空数组。但是当我手动选中/取消选中每个选项时, $scope.selectedAccounts 会给我正确的结果。

最佳答案

这是我的做法:

$scope.context = {accounts : :[]};// init is important to place the variable in that scope on not in a child
<div ng-repeat="account in context.accounts">
<input ng-model="account.lastchecked" ng-checked="account.lastchecked"
ng-true-value="true" ng-false-value="false" type="checkbox">
</div>

NG-true-value 和 ng-false-value 确保该值将是 bool true/false 而不是字符串。

获取 selectedAccount 后,您只需使用 lastchecked==true 搜索并过滤帐户

中间对象上下文是为了避免范围问题,范围继承在简单字段上失败。这是javascript的限制。在 angularJS 中,这称为 DOT 表示法。

关于javascript - 复选框无法与 ng-repeat、AngularJs 一起正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37003273/

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