ng-class不在angularjs中工作

时间:2015-11-05 11:44:13

标签: javascript jquery html angularjs angularjs-scope

我想使用angularjs(app.js)更改div的类名我遵循了这个answer但是我的视图中的类名没有改变。

这是我的观点

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

这是我的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");
                }
            }
        });
    });

我在做什么错,我该如何解决?

2 个答案:

答案 0 :(得分:2)

注意:您的代码适用于我,无需任何修改。

以下也应该工作:

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

此外,您可以使用class="{{className}}"

使其更简单

我到处都使用className,因为class是js-reserved字 例如,一些缩小器将失败。

答案 1 :(得分:1)

&#13;
&#13;
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";
    };
});
&#13;
.red {
  background-color: red;
}

.blue {
  background-color: blue;
}

.red, .blue {
  width: 200px;
  height: 200px;
}
&#13;
<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>
&#13;
&#13;
&#13;