每当用户更改输入时,AngularJS 中的 ng-change 指令都会评估给定的表达式。每次更改时,都会触发ngChange指令并立即评估表达式。JavaScript onChange事件仅在更改结束时触发(当用户离开表单元素或按下 <Enter> 键时)。
注意- 该指令还要求存在 ngModel。
<element ng-change="expression">..Content..</element>
在您的 Angular 项目目录中创建一个文件“ ngChange.html ”并复制粘贴以下代码片段。
<!DOCTYPE html> <html> <head> <title>ngChange Directive</title> <script xx_src="https://cdn.staticfile.org/angularjs/1.6.9/angular.min.js"> </script> </head> <body style="text-align: center;"> <h1 style="color:green"> Welcome to nhooo.com </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 文件运行即可。您将在浏览器窗口中看到以下输出。