Zabs
Zabs

Reputation: 14142

Have input checkbox toggle checked/unchecked in AngularJS 1.x

I am still new to AngularJS, I am trying to have a simple function that will toggle a checkbox on/off when clicked. So a clicked li element in the code below will either set that checkbox to on or off.

Can anyone suggest the best way to do this using AngularJS, I know jQuery would be simple but i'm trying to do this in the Angular way.

my html template

    <ul>
        <li ng-repeat="page in rule.pages" ng-click="toggleNetwork(page.id); ruleForm.$setDirty()">
            <span class="pull-left"><i class="check material-icons nomargin">{{rule.pages.indexOf(page.id) >= 0 ? 'check_box' : 'check_box_outline_blank'}}</i></span>
        </li>
    </ul>   

my Controller scope logic code

$scope.toggleNetwork = function(networkId) {
   // function called when checkbox clicked

}

Upvotes: 0

Views: 2726

Answers (2)

Pedro Vaz
Pedro Vaz

Reputation: 820

IF you just want the checkbox to toggle on/off, you don't really need to do anything. Angular will do it for you out of the box.

you only need a boolean variable in your controller, like this:

//myController.js

$scope.myCheckboxValue = false;

And your html should be something like this:

//myTemplate.html

<input type="checkbox" ng-model="myCheckboxValue">

Whenever you click the checkbox, the changes will already be reflected on myCheckboxValue.

Upvotes: 1

pato
pato

Reputation: 908

I don't see checkbox in your html so I'm assuming that you want to li tag working as checkbox.

You can do it that way, if page can have additional property:

$scope.toggleNetwork = function(network) {
   network.toggle = !network.toggle;
}

If you don't want to add property to network model you can store toggled networks in array;

$scope.toggledNetworks = [];
$scope.toggleNetwork = function(networkId) {
   var index = $scope.toggledNetworks.indexOf(networkId);
   if (index === -1) 
       $scope.toggledNetworks.splice(index, 1);
   else 
       $scope.toggledNetworks.push(networkId)
}

Then if you want to check if network is toggled you can use function:

$scope.isToggled = function(networkId) {
    return $scope.toggledNetworks.indexOf(networkId) !== -1;
}

Note:

rule.pages.indexOf(page.id)

Will always return -1. Pages contains objects, you want index of property of one object which is not in this array

Upvotes: 0

Related Questions