3

In this basic example of 2 input fields, I am updating the model on blur. The difference between the 2 fields is one has the required attribute and the other does not.

I'm watching for a change on the model and dumping out the $scope.user property. I have noticed that when the field is NOT required, I change the value from any string back to an empty string, and the model updates as empty. However, the required field updates as undefined.

I don't see anything particular in the docs that would cause this. Can anyone shed some light?

<div ng-app="app" ng-controller="Ctrl">
    <input name="name" ng-model="user.name1" ng-model-options="{updateOn: 'blur'}" />
    <input name="name" ng-model="user.name2" ng-model-options="{updateOn: 'blur'}" required />
</div>
<script>
var app = angular.module("app", []);
app.controller("Ctrl", ["$scope", function ($scope) {
    $scope.user = {
        name1: "",
        name2: ""
    };

    $scope.$watchGroup(["user.name1", "user.name2"], function (value) {
        console.log($scope.user);
    });
}]);
</script>

http://jsfiddle.net/3h8o1yrz/

1 Answer 1

2

In AngularJS, if there are validations on an input, by default ng-change will not be fired unless all validations are passed.

However, you can alter this behavior by ng-model-options (https://docs.angularjs.org/api/ng/directive/ngModelOptions).

Try this:

<input name="name" ng-model="user.name2" ng-model-options="{updateOn: 'blur', allowInvalid: true}" required />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.