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?

3
  • You need to call a service in your back-end from within Angular, and then use the result in your Controller. Commented Oct 3, 2016 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 Commented Oct 3, 2016 at 17:05
  • Right. Don't do that. It circumvents AngularJS, which is why you are having problems. Commented Oct 3, 2016 at 17:34

1 Answer 1

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.

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.