1

I have a text box which shows up as part of a form. Data is available through ng-model only for a few form fields.If the form fields are empty then on form submission, null is sent to the server. I want to have a placeholder value, like "No value yet" if it is an empty text box. If the user puts in value or edits value, then I need to be able to read that value and then send that as part of form submission. How do I achieve this using ng-if ? Thank You.

user3044240
  • 621
  • 19
  • 33
  • I dont think this is something that should (or even can?) be solved with ng-if. You could assign a click event to your button and assign the value there if it is null. – Marie Feb 18 '16 at 21:33
  • Form displays with values that it has got from controller. They are already there. I just want some text to be displayed if while rendering the form, any of the text boxes are empty. – user3044240 Feb 18 '16 at 21:36
  • 1
    Oh, I see. Couldnt you just modify the model when the controller is initialized then? – Marie Feb 18 '16 at 21:39
  • @Toni I would like to do it within the view and send the whole form on ng-submit. – user3044240 Feb 18 '16 at 21:42

1 Answers1

2

ng-if directive does create a child scope when rendering element on wherever it has placed. But newly created scope is prototypically inherited from parent scope.

So you should follow Dot Rule(have properties inside object) while defining ng-model in such case, so that prototypal inheritance rule will get followed.

Like create $scope.model = {} object and placed all the form properties in it.

<form name="myForm" ng-submit="save()" ng-if="showForm">
   <input name="firstName" ng-model="firstName"/> First Name
   <input name="lastName" ng-model="lastName"/> Last Name
   <input type="submit" value="Save"/>
</form>

Or you could also use controllerAs pattern while defining & using controller. You could find how controllerAs will work in this case, in below linked answer.

You could find detailed explanation here

Community
  • 1
  • 1
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • @dfsq yes..that has been there inside the linked answer.. Thanks for heads man. :-) – Pankaj Parkar Feb 18 '16 at 21:40
  • My code is like this: `
    ` I want text to be a string like "No information yet" if text box is empty.
    – user3044240 Feb 18 '16 at 21:40
  • @user3044240 could you just not have place holder text set before hand. If the property of your object person is empty, you will see the No info found message, otherwise you would see the value from the property. – Chris Feb 18 '16 at 22:05