Sloganho
Sloganho

Reputation: 2111

angular.js ng-class if-then statement not working

I'm relatively new to angularjs. I'm trying to use the ng-class to set a bootstrap nav-tab as active if it's the one that's currently selected.

            <ul class="nav nav-tabs nav-stacked nav-pills" role="tablist" ng-repeat="category in editor.categories">
                <li ng-model='value.[[category.id]]' ng-class="[[category.id]] == [[currentTab]] ? 'active' : 'innactive'">
                    <a class="btn-md" ng-click="changeTab([[category]])" href="">[[category.name]]</a>
                </li>
            </ul>

In the snippet below, category.id = 1456 and currentTab = 1456 but for some reason, it still has the innactive class set. From what I understand, the if-then statement would be like this if (1456 == 1456) class = 'active'; Does anyone have any idea of what's going on or a better way I could go about doing this to have it work? Any suggestions would be greatly appreciated. Thanks.

Snippet of my html that is not working

Upvotes: 0

Views: 404

Answers (2)

Greg Lafrance
Greg Lafrance

Reputation: 758

This sample code works, hope it helps:

angular.module('myApp', [])
    .controller('myController', function ($scope) {
        $scope.currentTab = 1;
        $scope.editor = {
            "categories": [
                {"id": 1, "name": "cars"},
                {"id": 2, "name": "boats"},
                {"id": 3, "name": "planes"}
            ]
        };
    });

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <style>
        .active {
            color: green;
        }
        .innactive {
            color: lightgrey;
        }
    </style>
</head>
<body ng-controller="myController">
    <ul ng-repeat="category in editor.categories">
        <li ng-class="category.id == currentTab ? 'active' : 'innactive'">
            <a href="">{{category.name}}</a>
        </li>
    </ul>
    <script src="../angularjs/angularjs_1.2.5/angular.js"></script>
    <script src="test.js"></script>
</body>
</html>

Upvotes: 1

swlim
swlim

Reputation: 452

Would love a comment to ask this but I do not have the reputation yet.

Just out of curiosity, have you tried the triple equal signs?
[[category.id]] === [[currentTab]] ? 'active' : 'innactive'"

and if making it '===' still doesn't work meaning to say that the both of them are of different types. If that's the case then you might want to look into making them both int by something like parseInt()

Upvotes: 1

Related Questions