Search code examples
htmlcssangularjsng-class

CSS styles doesn't apply when using ngClass


I have a problem with dynamically CSS updating. This is my HTML code:

<!DOCTYPE html>
<html lang="en" ng-app="ListItems">
<head>
    <meta charset="utf-8">
    <title>Test project</title>
    <link rel="stylesheet" href="Content/bootstrap.css">
    <link rel="stylesheet" href="Content/style.css">
</head>
<body ng-controller="ListController as list">
    <h1>To-do list</h1>

    <div id="main">
        <article ng-repeat="item in items track by $index" ng-class="{{item.IsCompleted ? 'completed' : 'uncompleted'}}">
            <p>{{item.Description}}</p>
            <footer>
                <small>
                    Is completed: <input type="checkbox" ng-checked="{{item.IsCompleted}}" ng-click="complete($index)" />
                </small>
            </footer>
        </article>
    </div>

    <script src="Scripts/angular.js"></script>
    <script src="Scripts/jquery-3.1.1.js"></script>
    <script src="Scripts/script.js"></script>
</body>
</html>

And now I want to apply the following css styles if item is completed:

.completed {
    background-color: red;
}

But nothing happened.


Solution

  • Try to use the correct ng-class syntax and ensure that .completed CSS class is available due to your CSS declarations. Here is a simple working fiddle which will help you. Compare it with your solution. Please take a look at the ng-class documentation of AngularJS.

    <article ng-repeat="item in items track by $index" 
             ng-class="{'completed': item.IsCompleted, 'uncompleted': !item.IsCompleted}">
        <p>{{item.Description}}</p>
        <footer>
            <small>
                Is completed: 
                <input type="checkbox" 
                       ng-checked="{{item.IsCompleted}}" 
                       ng-click="complete($index)" />
            </small>
        </footer>
    </article>