AngularJS ng-change 指令

定义和用法

ng-change 指令告诉 AngularJS 当 HTML 元素的值发生变化时要执行的操作。

ng-change 指令要求存在 ng-model 指令。

AngularJS 中的 ng-change 指令不会覆盖元素的原始 onchange 事件,ng-change 表达式和原始 onchange 事件都将被执行。

ng-change 事件在值每次发生变化时触发。它不会等到所有更改都完成,或者当输入框失去焦点时才触发。

ng-change 事件只有在输入值实际发生变化时才会触发,而不是通过 JavaScript 进行的更改。

实例

当输入框的值发生变化时,执行一个函数:

<body ng-app="myApp">
<div ng-controller="myCtrl">
    <input type="text" ng-change="myFunc()" ng-model="myValue" />
    <p>Input field has changed {{count}} times.</p>
</div>
<script>
angular.module('myApp', [])
.controller('myCtrl', ['$scope', function($scope) {
    $scope.count = 0;
    $scope.myFunc = function() {
        $scope.count++;
    });
});
</script>
</body>

Try it yourself

Syntax

<element ng-change="expression</element>

Support <input>,<select> and <textarea>.

Parameters

Parameters Description
expression Expression to be executed when the value of the element changes.