0

I'm currently writing an application in AngularJS, and I've stumbled across a problem while using ng-model with input fields.

In the case that a user does not enter any text in one input field, is there any way to bind a default value to the ng-model? A sample of the code is shown below:

<input class="formInput" placeholder="{{ testVar.hasName.name }}" type="text" id="nameUpdate" ng-model="upd.name">

The idea is a user will be updating data. The placeholder will show the existing data, in this case the name, and updating this field will bind to the model. However, if a user does not wish to update this particular field, how can I bind the existing value to the model? I've noticed giving the input a value="xyz" prevents the ng-model from working properly.

I should note defining this information in the controller as a default is not an acceptable solution, as the data within testVar will vary.

Thanks in advance for any help.

1
  • why do you show existing data as placeholder, and not just as value in the textbox ? Commented Mar 13, 2017 at 21:10

1 Answer 1

0

Not the best practice, but you can init a default value with the help of ng-init:

<input class="formInput"
       placeholder="{{testVar.hasName.name}}"
       type="text"
       id="nameUpdate"
       ng-init="upd.name='defaultTextHere'"
       ng-model="upd.name">
Sign up to request clarification or add additional context in comments.

3 Comments

So this seems to be what I'm looking for, but is it possible to bind a variable to this? ng-init=" '{{testVar.hasName.name}}' " holds the string correctly, however just ng-init="{{testVar.hasName.name}}" does not send the value to my controller.
Gave it a try, printing upd.name in an alert gives undefined?
Still undefined :(

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.