我们如何在angularjs中获取所选复选框的数组ID?

时间:2015-11-24 12:09:35

标签: angularjs checkbox

我正在尝试获取所选复选框的数组ID但无法获取数组。我需要格式为["302740", "42006", "331497"]

的数组

这是我的app.js

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

function Ctrl($scope) {     

    $scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];
    $scope.brandlist = [];

    $scope.get = function (val) {
        console.log(val);

        var idx = $scope.brandlist.indexOf(val);

        if (idx > -1) 
            $scope.brandlist.splice(idx, 1);                
        else 
            $scope.brandlist.push(val);

        console.log($scope.brandlist);        
        // should come like selected array ["302740", "42006", "331497"] 
    }

}

这里是html

<div ng-controller="Ctrl">
    <span ng-repeat="(key,val) in categories">
        <label class="checkbox" for="{{key.tid}}">
            <input type="checkbox" ng-change="get(val.tid)" ng-model="brandlist[val.tid]" ng-checked="brandlist.indexOf(val.tid) > -1" name="group" id="{{val.tid}}" />
            {{val.name}}         
        </label>
    </span>
</div>

plunker

2 个答案:

答案 0 :(得分:0)

考虑尝试这个

$scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];

$scope.selecetedCategories = function toggleSelection(category){
   var idx = $scope.selectedCategories.indexOf(category);
      if(idx > -1){
        $scope.selecetedCategories.splice(idx,1);
      }
      else{
        $scope.selecetedCategories.push(category);
      }
};

您可以像这样打印所选类别

console.log($scope.selecetedCategorie);

你的HTML:

<input type="checkbox" name="selectedCategories"
 value="{{category}}" ng-checked="selectedCategories.indexOf(category) >
 -1" ng-click="toggleSelection(category)"/>

答案 1 :(得分:0)

如果您不担心操纵源数组,可以使用它来维护状态。

HTML

<div ng-controller="Ctrl">
    <span ng-repeat="(key,val) in categories">
        <label class="checkbox" for="{{key.tid}}">
            <input type="checkbox" ng-model="val.checked" name="group" id="{{val.tid}}" />
            {{val.name}}         
        </label>
    </span>
</div>

JS:

$scope.categories = [ {"tid":"302740","name":"2 BE 3"},{"tid":"42006","name":"A Line"},{"tid":"331497","name":"Activa"} ];

// get the selected categories
var selectedCategories = $scope.categories.filter(function(itm) {
   return itm.checked;
});