Search code examples
javascriptangularjsng-class

Checkbox conditional class in Angular is not working


In this simple example, I am trying to add a class to checkbox input if it is checked. I don't know why this simple example is not working. Can someone help me out?

<html>
<head> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"></script>  
</head> 
<body ng-app="myApp" ng-controller="myCtrl"> 
    <input type="checkbox" ng-model="isChecked" ng-class="{peter: isChecked}" />
    <script>
        //Module Declaration
        var app = angular.module('myApp',[]);
        //Controller Declaration
        app.controller('myCtrl',function($scope){
            //No code
        });
    </script> 
</body> 
</html> 

Solution

  • Please provide more code. I'll delete this answer if this is a typo but you are missing /> in the `input field.

    Change <input type="checkbox" ng-class="{peter: isChecked}" to <input type="checkbox" ng-class="{peter: isChecked}" />.

    Just change your line

    app.controller = ('myCtrl',function($scope){
        //No code
    });
    

    to

    app.controller('myCtrl',function($scope){
        //No code
    });
    

    Your controller was declared with the wrong syntax. There is dev console in every browser. You should fire it and first see the errors :-)