2016-09-19 29 views

回答

0

您可以使用Angular.js的Checklist-model。这是非常有用:

var app = angular.module("app", ["checklist-model"]); 
 
app.controller('Ctrl1', function($scope) { 
 
    $scope.roles = [ 
 
    'guest', 
 
    'user', 
 
    'customer', 
 
    'admin' 
 
    ]; 
 
    $scope.user = { 
 
    roles: ['user'] 
 
    }; 
 
    $scope.checkAll = function() { 
 
    $scope.user.roles = angular.copy($scope.roles); 
 
    }; 
 
    $scope.uncheckAll = function() { 
 
    $scope.user.roles = []; 
 
    }; 
 
    $scope.checkFirst = function() { 
 
    $scope.user.roles.splice(0, $scope.user.roles.length); 
 
    $scope.user.roles.push('guest'); 
 
    }; 
 
    $scope.showCheckedOnes = function() { 
 
    var checkedBoxes = ""; 
 
    for (var i = 0; i < $scope.user.roles.length; i++) { 
 
     checkedBoxes += $scope.user.roles[i] + " "; 
 
    } 
 
    alert(checkedBoxes); 
 
    }; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<script src="https://vitalets.github.io/checklist-model/checklist-model.js"></script> 
 

 
    <div ng-app="app"> 
 
    <div ng-controller="Ctrl1"> 
 

 
     <label ng-repeat="role in roles"> 
 
     <input type="checkbox" checklist-model="user.roles" checklist-value="role"> {{role}} 
 
     </label> 
 

 
    <div> 
 
    <div> 
 
    <button ng-click="checkAll()" style="margin-right: 10px">Check all</button> 
 
    <button ng-click="uncheckAll()" style="margin-right: 10px">Uncheck all</button> 
 
    <button ng-click="checkFirst()" style="margin-right: 10px">Check first</button> 
 
    <button ng-click="showCheckedOnes()" style="margin-right: 10px">Show checked ones</button>

+0

感谢您花费宝贵的时间来解决我的问题。 –

+0

不客气 – webmaster

0

您可以定义数组值并映射到html。

$scope.checkbox = []; 

HTML

<input ng-model="checkbox[0] type="checkbox" /> 
<input ng-model="checkbox[1] type="checkbox" /> 
<input ng-model="checkbox[2] type="checkbox" /> 
<input ng-model="checkbox[4] type="checkbox" /> 

,也可以定义为复选框对象,变化选择框[指标]到复选框[名]。

1

我用这一小段代码。随意采取。

在你的控制器:

$scope.sentinel = []; 

$scope.toggleSelection = function(value) {    
      // Bit trick, equivalent to "contains" 
      if (~$scope.sentinel.indexOf(value)) { 
       var idx = $scope.sentinel.indexOf(value); 
       $scope.sentinel.splice(idx, 1); 
       return; 
      } 

      $scope.sentinel.push(value); 
     }; 

然后在你的HTML:

<span ng-repeat="key in $scope.yourarray"> 
    <md-checkbox style="margin-left:30px;" aria-label="Select item" 
    ng-click="toggleSelection(key)"><span>{{ key }}</span></md-checkbox> 
    <br/> 
</span> 

这可以让你有任何大小的阵列,通过sentinel阵列已经登记检查的值。如果再次检查一个框,toogleSelection将阻止您再次添加值。

相关问题