jiexishede jiexishede - 1 month ago 15
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">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>

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

button {
width: 200px;
height: 50px;
background-color: gold;
}
</style>

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

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

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

</body>
<script>
var app = angular.module('xxx',[]);
app.controller('ooo',['$scope',function ($scope) {
$scope.isRed = false;
$scope.changeColor = function () {
$scope.isRed = !$scope.isRed;
}
}]);
</script>
</html>


Is there another way to realize it?

Answer

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.

Comments