Shevek
Shevek

Reputation: 4063

AngularJs and ASP.NET MVC 5 - ng-model overriding SELECT selected OPTION

Following on from my previous question here:

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

I am now having the same problem with a SELECT.

I have a form built using ASP.NET MVC 5 using @Html.EnumDropDownListFor 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 function using Angular (1.4.7) which means the SELECT is now decorated with ng-model to enable the Angular function to use the selected value.

e.g.:

@Html.EnumDropDownListFor(m => m.MyEnum, 
                          new { @class="form-control", ng_model="obj.myEnum" })

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

Viewing the source in the browser shows that the selected option is set correctly from the MVC model but there is an extra option which is being selected:

<select class="form-control ng-pristine ng-valid ng-touched" 
        name="MyEnum" ng-model="obj.myEnum">
    <option value="? undefined:undefined ?"></option>
    <option value="0">Please select</option>
    <option selected="selected" value="1">Option1</option>
    <option value="2">Option2</option>
</select>

How can I prevent this so that Option1 stays selected?

Using the directive from my previous question does not work as a SELECT does not have a value attribute.

The ng_init also does not work on a SELECT

Upvotes: 3

Views: 1617

Answers (1)

tasseKATT
tasseKATT

Reputation: 38490

Here is a directive that should help in your case:

app.directive('initSelect', ['$parse', function($parse) {
  return {
    link: function(scope, element, attrs) {

      var select = element[0];

      if (!select.options.length || !attrs.ngModel) return;

      var initialValue = select.options[select.selectedIndex].value;

      $parse(attrs.ngModel).assign(scope, initialValue);
    }
  }
}]);

It will first retrieve the value of the selected option, in your case "1". It will then use the $parse service to set the correct ngModel value.

After this the select should render correctly.

Demo: http://plnkr.co/edit/2VvkGfsPW94SPSVW6iUN?p=preview

Upvotes: 5

Related Questions