0

Scenario

I am using Angular, purely for validation on my front-end, and MVC model binding

Example

<div ng-class="{'has-error': Contact.FirstName.$invalid}">
    <input type="text"
           name="@Html.NameFor(m => m.FirstName)"
           id="@Html.IdFor(m => m.FirstName)"
           value="@Model.FirstName"
           ng-model="model.person.firstName"
           required />
</div>

Problem

value is populated by MVC on postback, but because model.person.firstName is initially null, the value is cleared when the document finishes loading, and angular has flushed all of it's magic into the view.

Question

How can I keep ng-model (in order to keep validation working) and pre-populate the value of the field?

Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
  • You need to call a service in your back-end from within Angular, and then use the result in your Controller. – Amy Blankenship Oct 03 '16 at 16:39
  • @AmyBlankenship data is not being delivered to the front-end via a service. That would be trivial. The problem is that the values are being bound to the view, long before angular get's a hold of it, so angular just ignores what's in the view and does it's thing – Matthew Layton Oct 03 '16 at 17:05
  • Right. Don't do that. It circumvents AngularJS, which is why you are having problems. – Amy Blankenship Oct 03 '16 at 17:34

1 Answers1

0

The values have to be initialised in the controller and not in the view.

Option 1 :

You can try ng-init. See this issue

Option 2 :

Another way is to create a service directly in the .cshtml file in a <script></script> tag. Filling the data of the service with Razor and then get this values with your Angular controller.

In my opinion the second way is cleaner.

Community
  • 1
  • 1
Maxime Gélinas
  • 2,202
  • 2
  • 18
  • 35