【问题标题】:Checkbox is not working properly with ng-repeat, AngularJs复选框无法与 ng-repeat、AngularJs 一起正常工作
【发布时间】:2016-05-03 20:02:41
【问题描述】:

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

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

在控制器中,我选择的 id 为:

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

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

【问题讨论】:

    标签: javascript angularjs checkbox


    【解决方案1】:

    我会这样做:

    $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 确保值将是布尔值 true/false 而不是字符串。

    在获得 selectedAccount 后,您只需使用lastchecked==true 搜索.filter 帐户

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

    【讨论】:

    • $scope.context = {accounts : :[]};这里的帐户是 $scope.accounts 对吗?
    • 是的,但它是故意的,正如我在上一句中所说,这避免了范围问题,如果您在控制器声明和 ng-repeat 之间使用某些指令,您的代码可能无法正常工作。由于ngIf,这里有反复出现的情况。
    【解决方案2】:

    通过这个

    var jimApp = angular.module("mainApp",  []);
    
    jimApp.controller('mainCtrl', function($scope){
      $scope.selectedAccounts = {"3":true};
      $scope.accounts = [{id:1, name:"account1", checked: true}, {id:2, name:"account2"}, {id:3, name:"account3"}]
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    
    
    <div ng-app="mainApp" ng-controller="mainCtrl">
      <div ng-repeat="account in accounts">
        <input ng-model="selectedAccounts[account.id]"              
        ng-checked="selectedAccounts[account.id]" type="checkbox">{{account.name}}       
      </div>
      <div>{{selectedAccounts}}</div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      • 2017-10-07
      • 2016-09-12
      相关资源
      最近更新 更多