【问题标题】:get array values based on checkbox根据复选框获取数组值
【发布时间】:2016-03-20 19:32:53
【问题描述】:

我的情况是有 3 个复选框(“最初选中”)。由于它是 3 复选框,因此它将使用 ng-repeat 3 次并循环除法。现在,一旦我取消选中任何复选框,它应该显示 div 2 次。到目前为止,

$scope.items = [
    {id: 0, title: "apple",selected:true},
    {id: 1, title: "orange",selected:true},
    {id: 2, title: "grapes",selected:true},     
];

在每个复选框的 ng-click 上,我调用了一个函数 test("apple")。

$scope.test = function(vals) {
    $scope.vl=[];
    for(var i=0;i<$scope.items.length;i++) {
        if($scope.items[i].title == vals) {
            console.log("dnt push");
        }
        else {
            $scope.vl.push({
                id: $scope.items[i].id,
                title: $scope.items[i].title,
                selected:true                      
            });
        }
    } 
    console.log("vl array");
    console.log($scope.vl);
}

我面临的问题是它在第一次取消选中时工作正常,但在我多次取消选中时却不行。当我选中未选中时,它没有加载 div。

在我使用的 HTML 中,

<div ng-repeat="item in vl"> some tags </div>

【问题讨论】:

  • 你到底想做什么?

标签: angularjs checkbox ng-repeat


【解决方案1】:

不太清楚你的问题,但希望我的回答能给你一些提示。

plunker demo

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

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.items = [{
    id: 0,
    title: "apple",
    selected: true
  }, {
    id: 1,
    title: "orange",
    selected: true
  }, {
    id: 2,
    title: "grapes",
    selected: true
  }];
});
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.8/angular.js" data-semver="1.4.8"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>
  <div ng-repeat="item in items">
    <input type="checkbox" ng-model="item.selected">{{item.title}}
  </div>
  {{items | json}}
</body>

</html>

【讨论】:

    【解决方案2】:

    当且仅当您想将被检查的项目放入数组中:

    http://plnkr.co/edit/DvoPBBvKf3AhYM4qcBhx?p=preview

    html

    <div ng-repeat="item in items">
      <input type="checkbox" 
            ng-model="item.selected" ng-click="test(item.title)"> {{item.title}}
    </div>
    

    控制器

    $scope.test = function(vals) {
      $scope.vl=[];
      $scope.vlChecked=[];
      for(var i=0;i<$scope.items.length;i++) {
        if($scope.items[i].selected) {
          $scope.vlChecked.push({
            id: $scope.items[i].id,
            title: $scope.items[i].title,
            selected:true                    
          });
        }
      } 
    
      console.log("vlChecked array");
      console.log(JSON.stringify($scope.vlChecked));
    
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 2019-12-07
      • 1970-01-01
      • 2011-08-14
      相关资源
      最近更新 更多