如何使用AngularJS在点击按钮后改变其颜色
创建了一个HTML按钮,任务是在AngularJS的帮助下改变按钮的背景颜色。这个任务可以通过ng-click指令来完成,该指令有助于在按钮或任何特定的HTML元素被点击时切换内容的显示。在这里,ng-controller指令被应用于向应用程序添加控制器,可以利用它来添加方法、函数和变量,反过来,这些方法、函数和变量可以在一些事件中被调用,如点击等,以执行某种动作。
方法:在这种方法中,我们将尝试改变按钮的class或id,而这些classes/IDs的CSS将改变按钮的背景颜色。
例子1:在这个例子中,使用AngularJS中的ng-click指令将类从红色改为绿色。
<!DOCTYPE HTML>
<html>
<head>
<script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<script>
var myApp = angular.module("app", []);
myApp.controller("controller", function(scope) {
scope.myButton = 'red';
scope.changeCol = function() {
scope.myButton = "green";
};
});
</script>
<style type="text/css">
.red {
background: red;
color: white;
}
.green {
background: green;
color: white;
}
</style>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
How to change the color
of the button in AngularJS
</h3>
<div ng-app="app">
<div ng-controller="controller">
<button ng-click="changeCol()"
class="{{myButton}}">
Click to change
</button>
</div>
</div>
</body>
</html>
输出:
例子2:在这个例子中,使用AngularJS中的ng-click指令,将按钮的id从蓝色改为绿色。
<!DOCTYPE HTML>
<html>
<head>
<script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
</script>
<script>
var myApp = angular.module("app", []);
myApp.controller("controller", function(scope) {
scope.ID = 'blue';
scope.changeCol = function() {
scope.ID = "green";
};
});
</script>
<style>
#blue {
background: blue;
color: white;
}
#green {
background: green;
color: white;
}
</style>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3>
How to change the color of
the button in AngularJS
</h3>
<div ng-app="app">
<div ng-controller="controller">
<button ng-click="changeCol()"
id="{{ID}}">
Click to change
</button>
</div>
</div>
</body>
</html>
输出: