AngularJS – ng-change 指令
angularjsweb developmentfront end technology更新于 2026/1/7 3:07:17
每当用户更改输入时,AngularJS 中的 ng-change 指令都会执行给定的表达式。每次更改时,都会触发 ngChange 指令并立即执行表达式。JavaScript 的 onChange 事件仅在更改结束时触发(当用户离开表单元素或按下 <Enter> 键时)。
注意 − 此指令还需要 ngModel 存在。
语法
<element ng-change="expression">..Content..</element>
示例 − ngChange 指令
在 Angular 项目目录中创建文件"ngChange.html",并复制粘贴以下代码片段。
<!DOCTYPE html>
<html>
<head>
<title>ngChange Directive</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body style="text-align: center;">
<h1 style="color:green">
Welcome to Tutorials Point
</h1>
<h2>
AngularJS | ngChange Directive
</h2>
<div ng-app="demo" ng-controller="app">
Check to show/hide details
<input type="checkbox" ng-change="show()" ng-model="check">
<br><br>
<div style="padding:50px; margin-left: auto; margin-right: auto; border:1px solid black; width:30%;color:green" ng-show='result'>
Start Learning the new Angular JS features now...
</div>
</div>
<!-- Script for passing the values and checking... -->
<script>
var app = angular.module('demo', []);
app.controller('app', function ($scope) {
$scope.show = function () {
if ($scope.check == true)
$scope.result = true;
else
$scope.result = false;
}
});
</script>
</body>
</html>
输出
要运行上述代码,只需打开您的文件并将其作为普通 HTML 文件运行即可。 您将在浏览器窗口中看到以下输出。
示例 2
在您的 Angular 项目目录中创建文件"ngChange.html",并复制粘贴以下代码片段。
<!DOCTYPE html>
<html>
<head>
<title>ngChange Directive</title>
<script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
</head>
<body style="text-align: center;">
<h1 style="color:green">
Welcome to Tutorials Point
</h1>
<h2>
AngularJS | ngChange Directive
</h2>
<div ng-app="demo" ng-controller="prop">
<div>
Are you a developer:
<input type="checkbox" ng-model="isTrue" ng-change="cnt=cnt+1" ng-init="cnt=0"/>
</div>
Count: {{cnt}}
<pre>{{isTrue}}</pre>
</div>
<!-- Script for passing the values and checking... -->
<script>
var app = angular.module("demo", []);
app.controller('prop', ['$scope', function ($app) {
$app.isTrue = false;
}]);
</script>
</body>
</html>
输出
要运行上述代码,只需打开您的文件并将其作为普通 HTML 文件运行即可。您将在浏览器窗口中看到以下输出。

