0

I want to change the class name of div using angularjs (app.js) I followed this answer but the class name is not changing in my view.

Here is my view

<div ng-class="class">{{class}}</div>
<button ng-click="changeClass()">Change Class</button>

Here is my app.js

var app = angular.module('myApp', ['ngRoute', 'ngAnimate', 'toaster']);

app.controller("myApp", function ($scope) {
    $scope.class = "red";
    $scope.changeClass = function () {
        alert('a');
        if ($scope.class === "red")
            $scope.class = "blue";
        else
            $scope.class = "red";
    };
});
app.config(['$routeProvider',
        function ($routeProvider) {
            $routeProvider.
            when('/', {
                    title: 'Dashboard',
                    templateUrl: 'views/dashboard.html',
                    controller: 'authCtrl',
                    role: '0'
                })
                .otherwise({
                    redirectTo: '/login'
                });
        }
    ])
    .run(function ($rootScope, $location, Data) {
        $rootScope.$on("$routeChangeStart", function (event, next, current) {
            var nextUrl = next.$$route.originalPath;
            if (localStorage.getItem("serviceUserId") === null) {
                $location.path("/login");
            } else {

                if (nextUrl == '/') {
                    $location.path("/dashboard");
                }
            }
        });
    });

What is the mistake i am doing and how can i fix it ?

Community
  • 1
  • 1
Biz Dev B
  • 383
  • 1
  • 6
  • 18

2 Answers2

2

Note: Your code works for me w/o any modifications.

Following should work also:

<div ng-class="{red: className === 'red', blue: className === 'blue'}">{{className}}</div>

Also, you can make it simpler with class="{{className}}"


I use className everywhere, because class is js-reserved word.
Some minifiers will fail with it, for example.

vp_arth
  • 14,461
  • 4
  • 37
  • 66
1

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

app.controller("myCtrl", function ($scope) {
    $scope.className = "red";
    $scope.changeClass = function () {
        alert('a');
        if ($scope.className === "red")
            $scope.className = "blue";
        else
            $scope.className = "red";
    };
});
.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.red, .blue {
  width: 200px;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="myCtrl">
    <div class="{{className}}">{{className}}</div>
    <button ng-click="changeClass()">Change Class</button>
  </div>
</div>
Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50