jiexishede jiexishede - 1 year ago 100
AngularJS Question

How to use the `ng-class` to add and remove the class?

I use the ng-class to add and remove the class by clicking the ` Button,' is not does not work? I use the Angular1.

What is the reason?

<html lang="en" ng-app="xxx">
<meta charset="UTF-8">

div {
width: 500px;
height: 500px;
background-color: black;
div.red {
background-color: red;

button {
width: 200px;
height: 50px;
background-color: gold;

<body ng-controller="ooo">
<script src="angular.js"></script>

<div ng-class="{red:isRed}" >xxxx</div>

<button ng-click="changColorIsRed()">O</button>

var app = angular.module('xxx',[]);
app.controller('ooo',['$scope',function ($scope) {
$scope.isRed = false;
$scope.changeColor = function () {
$scope.isRed = !$scope.isRed;

Is there another way to realize it?

Answer Source

You have a mistake in your code.

You define function changeColor but you use changColorIsRed in your ng-click attribute.

If you correct this to ng-click="changeColor()", your code will work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download