更新在angularjs中选中复选框值的数组

时间:2016-04-06 11:59:57

标签: javascript arrays angularjs

我有一个数组如下

var selected = [];

$scope.listA = [
  {
    name : "Sample 1"
  },
  {
    name : "Sample 2"
  },
  {
    name : "Sample 3"
  }
];

输入html元素是

<div ng-repeat="label in checkMode()">
    <input type="checkbox" checked> {{ label.name }}</input>
</div>

如何根据选中的复选框获取所选值的数组? 例如,我想获得以下选择的值

var selected = ["sample 1","sample 3"];

也可以更新阵列。

3 个答案:

答案 0 :(得分:0)

这是一个执行此操作的简单轻量级指令

http://vitalets.github.io/checklist-model/

答案 1 :(得分:0)

很容易..

在复选框中添加一个单击功能,希望这应该有用...参考链接... jsbin

<div ng-repeat="label in checkMode()">
   <input type="checkbox" checked ng-click="toggleSelection(label.name)> {{ label.name }}</input>
</div>
$scope.listA = {
    name : "Sample 1"
  },
  {
    name : "Sample 2"
  },
  {
    name : "Sample 3"
  }
];

$scope.selected=[];

  $scope.toggleSelection = function toggleSelection(selected) {
    var idx = $scope.selected.indexOf(selected);

    // is currently selected
    if (idx > -1) {
      $scope.selected.splice(idx, 1);
    }

    // is newly selected
    else {
      $scope.selected.push(fruitName);
    }
  };

答案 2 :(得分:0)

您可以使用ng-checked来实现此目标

var app = angular.module('my-app', [], function() {})

app.controller('AppController', function($scope) {
  $scope.selected = ['Sample 2'];

  $scope.listA = [{
    name: "Sample 1"
  }, {
    name: "Sample 2"
  }, {
    name: "Sample 3"
  }];

  $scope.toggleChecked = function(item) {
    var index = $scope.selected.indexOf(item.name);
    if (index == -1) {
      $scope.selected.push(item.name);
    } else {
      $scope.selected.splice(index, 1);
    }
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="my-app">
  <div ng-controller="AppController">
    <div ng-repeat="label in listA">
      <input type="checkbox" ng-checked="selected.indexOf(label.name) > -1" ng-click="toggleChecked(label)">{{ label.name }}
    </div>
    <pre>{{selected}}</pre>
  </div>
</div>