0

I am trying to using ng class ternary operator to toggle class when a check box is selected.

Here is the simple code: http://jsfiddle.net/vqmua1x2/

I am expecting text content to turn bold and unbold when check box is selected.

I am not able to find what is my mistake.

HTML code:

<div ng-app="myApp">
<div ng-controller="Ctrl1">
    <header>
            <h1>Problems</h1>

    </header>
    <div id="problems">
        <table>
            <tr>
                <td>
                    <input type="checkbox" ng-model="val1"/>
                </td>
                <td>prob1</td>
            </tr>
            <tr>
                <td>
                    <input type="checkbox" ng-model="val2"/> 
                </td>
                <td>prob2</td>
            </tr>
        </table>
    </div>

<div>
    <header>
            <h1>Orders</h1>

        <ul>
            <li ng-class="{{val1 }}? 'bold' : 'unbold'">prob1</li>
            <li ng-class="{{val2 }}? 'bold' : 'unbold'">prob2</li>
        </ul>
    </header>
</div>
     </div>

Javascript:

var myApp = angular.module('myApp', []);

myApp.controller('Ctrl1', ['$scope', '$rootScope', '$window', function ($scope, $rootScope, $window) {
    $scope.val1 = false;
    $scope.val2 = false;   
}]);

CSS:

.bold {
    font-style:none;
    font-weight:bold;
}
.unbold {
    font-style:none;
    font-weight:bold;
}
1
  • 1
    The first problem with your fiddle is you haven't even bootstrapped Angular correctly, there are errors in the console. The answer may be something like ng-class="{bold:val1}" but I haven't tested. Edit: updated your fiddle, that is the answer. jsFiddle Commented Jan 21, 2015 at 19:24

3 Answers 3

2
  • For the fiddle to work, select "no wrap - in body"
  • The correct syntax for ng-class is:

    <li ng-class="{ 'bold': val1, 'unbold': !val1 }">prob1</li>
    

With these changes the fiddle works: http://jsfiddle.net/hpwhb62d/

Sign up to request clarification or add additional context in comments.

Comments

1

The first problem with your fiddle is you haven't even bootstrapped Angular correctly, there are errors in the console.

Secondly, check the documentation for ng-class here - your javascript is not correct.

The ng-class could look like this:

<ul>
    <li ng-class="{bold:val1}">prob1</li>
    <li ng-class="{bold:val2}">prob2</li>
</ul>

jsFiddle

Comments

1

Should be like this.

<li ng-class="val1 ? 'bold' : 'unbold'">prob1</li>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.