In the previous post, we learnt how to bind custom error message to the form based on control state. In this post, we shall learn how to attach a custom trigger to update the model.
By default, change in content of the input element triggers the model update and validates the form. However, we can override this behavior by attaching ng-model-options directive with event name to the input element.
The values of the ng-model-options can be following
{updateOn : 'blur'}
- updates the model when this element loose focus{updateOn : 'mouseup'}
- updates the model when this element is clicked and mouse button is released{updateOn : 'default'}
- updates the model with default behavior, as and when the key is pressed{updateOn : 'default mousedown'}
- updates the model with default behavior, as and when the key is pressed or mousedown event fires on the elementIn the <script> block, we have a controller and an object defined with the $scope object.
<script>
var app = angular.module("app", []);
app.controller("CustomTriggerController", ["$scope", function ($scope) {
$scope.PD = {};
}]);
</script>
<div ng-app="app" ng-controller="CustomTriggerController">
<form name="myForm">
<p>
Username: <input type="text" ng-model="PD.username" required
ng-model-options="{updateOn : 'blur'}" />
</p>
Address: <input type="text" ng-model="PD.address" required
ng-model-options="{updateOn : 'default blur'}"/>
</form>
<hr />
<b>Username:</b> {{PD.username}} <br />
<b>Address:</b> {{PD.address}}
</div>
In the HTML block, we have Username text box, whose ng-model set as "PD.username"
and ng-model-options as "{updateOn: 'blur'}"
that means it's model will get updated only when blur event occurs (text box looses focus) on this element.
The Address text box has similar directives however ng-model-options set as "{updateOn : 'default blur'}"
that means it's model gets updated either default way (as and when the text box value changes) or on blur event occurs on this text box.
Output
Views: 13653 | Post Order: 54