如何使用angularjs检查复选框是否已选中

时间:2017-09-23 07:52:28

标签: javascript html angularjs

 <div  ng-repeat="sub in rolem.submenus" >
<input type="checkbox"  ng-model="hasChecked" ng-change="Menu_Dtls_Checkbox(sub)"/>{{sub}} <br/>
</div> 

和控制器是,

   $scope.Menu_Dtls_Checkbox=function(submenuname){
       if($scope.hasChecked){
           alert("checked");
       }
       else
       alert("Unchecked");

但它不起作用。请给出解决方案。

2 个答案:

答案 0 :(得分:1)

因为checkbox内有ng-repeatng-repeat会为创建的每个ng-model创建一个新的checkbox。因此,我建议您使用JSON对象来跟踪复选框的值,如下所示。

&#13;
&#13;
angular.module('app',[]).controller('mainCtrl', function($scope){
  $scope.rolem = {
       submenus:['xxx','yyy','zzz']
  };
  $scope.cbList = {};
  $scope.Menu_Dtls_Checkbox=function(submenuname){
    if($scope.cbList[submenuname]){
      alert("checked");
    }
    else{
     alert("Unchecked");
    }
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app' ng-controller='mainCtrl'>
 <div  ng-repeat="sub in rolem.submenus" >
   <input type="checkbox" ng-model="cbList[sub]" ng-change="Menu_Dtls_Checkbox(sub)"/>{{sub}} <br/>
   </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

您可以将hasChanged标志作为参数传递给您的函数:

<div  ng-repeat="sub in rolem.submenus" >
<input type="checkbox"  ng-model="hasChecked" ng-change="Menu_Dtls_Checkbox(sub, hasChecked)"/>{{sub}} <br/>
</div> 


$scope.Menu_Dtls_Checkbox=function(submenuname, hasChecked){
   if(hasChecked){
       alert("checked");
   }
   else{
     alert("Unchecked");
   }