gruberb gruberb - 1 year ago 83
AngularJS Question

How to check if any Checkbox is checked in Angular

Is there any function or ng-something to check if any of the displayed Checkboxes are checked?

I have the values through the ng-click="function()" and pass the values through. I can go by foot and check my array if any value is inside.

I want to activate/deactivate the "next"-button if any Checkbox is

What's the easiest way?

Answer Source

You can do something like:

        function ChckbxsCtrl( $scope , $filter ){

            $scope.chkbxs = [{label:"Led Zeppelin", val:false },
                             {label:"Electric Light Orchestra", val:false },
                             {label:"Mark Almond", val:false }];

            $scope.$watch( "chkbxs" , function(n,o){
                var trues = $filter("filter")( n , {val:true} );
                $scope.flag = trues.length;
            }, true );


And a template:

<div ng-controller="ChckbxsCtrl">
    <div ng-repeat="chk in chkbxs">
        <input type="checkbox" ng-model="chk.val" />
    <div ng-show="flag">I'm ON when band choosed</div>


UPDATE: Or you can go little bit different way , without using $scope's $watch() method, like:

$scope.bandChoosed = function() {
    var trues = $filter("filter")( $scope.chkbxs , {val:true} );
    return trues.length;

And in a template do:

<div ng-show="bandChoosed()">I'm ON when band choosed</div>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download