Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJs and ASP.NET MVC 5 - ng-model overriding textbox value

I have a form built using ASP.NET MVC 5 using @Html.TextBoxFor to populate the form with my model (e.g, after a form navigation or server side validation failure).

I have now introduced a client side address lookup using Angular which means some of the form fields are now decorated with ng-model to enable the Angular lookup to populate the searched address.

e.g.:

@Html.TextBoxFor(m => m.Town, new { @class="form-control", ng_model="address.town" })

Adding the ng-model now overrides the value set from the MVC model when the page is reloaded.

Viewing the source in the browser shows that the textbox value is set correctly to Town from the MVC model but Angular then comes along and populates it with address.town which is empty so the form displays no value.

How can I prevent Angular from doing this?

like image 280
Shevek Avatar asked Nov 05 '15 18:11

Shevek


1 Answers

You can use ng-init to force a value from MVC

<input name="Town" type="text" ng-model="address.town" ng-init="address.town= @Model.Town" />

@Html.TextBoxFor(m => m.Town, new { ng_model="address.town", ng_init="address.town= Model.Town" })

Alternatively, I use a directive which I found here https://stackoverflow.com/a/22567485/2030565

app.directive('input', function ($parse) {
    return {
        restrict: 'E',
        require: '?ngModel',
        link: function (scope, element, attrs) {
            if (attrs.ngModel) {
                val = attrs.value || element.text();
                $parse(attrs.ngModel).assign(scope, val);
            }
        }
}; });
like image 172
Jasen Avatar answered Oct 16 '22 16:10

Jasen