1

as in the title.. how to prevent such operations to happen? Here is a link to the official site, see the example. The variable user.name is bound to the first input userName and if the input is empty the object user.name is removed. How can I disable this functionality of angularjs?

10
  • Sample code perhaps and a description of the problem? Commented Mar 30, 2015 at 8:30
  • the code is on the example in the link... I didn't post my code because its the same as in the example. Commented Mar 30, 2015 at 8:34
  • Oh, I see what you are saying. The question could have been a bit clearer. OK, so what do you want to set user.name to? After all, if the input userName is empty, then the model should be empty? Commented Mar 30, 2015 at 8:36
  • Of course, once you set it once, it will keep it. Commented Mar 30, 2015 at 8:38
  • Here is a basic fiddle jsfiddle.net/yzg250uL Commented Mar 30, 2015 at 8:39

2 Answers 2

1

Try ng-model-options="{allowInvalid: true}" to update the model even for invalid entries.

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

Comments

0

You've got 2 option

  1. remove required from input tag it allows you to send back empty string to your backend

var app = angular.module('app', []);


app.controller('MyCtrl', function($scope) {
  $scope.params = {
    user: "John"
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyCtrl">
  <input name="userName" ng-model="params.user" />
  <hr/>
  <pre>{{params| json}}</pre>
</div>

  1. Option two validate your form before you send it to backend.

var app = angular.module('app', []);


app.controller('MyCtrl', function($scope) {
  $scope.user = {
    name: "John"
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>



<div ng-app="app" ng-controller="MyCtrl">
  <form name="someForm">
    <input name="userName" ng-model="user.name" required name="userName" />
    <span ng-show="someForm.userName.$error.required">User Name required</span>
    <br/>{{user | json}}
    <br/>

    <button type="submit" ng-disabled="someForm.$invalid">Submit</button>
  </form>
</div>

1 Comment

I want to send an Form with an empty input (an invalid input - as angular interprets it), later on an user will get that form and he will fill it. I used the solution which @Vinay K suggested, to use ng-model-options directive. Thanks for your help @Vinay K

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.