How to use ng-options with ng-model to bind with parent scope variable?

Issue

I’m using AngularJS along with UI-router. I’ve a parent state & a child. A parent state contains a variable which is initialized to null. In child state, I’ve displayed a dropdown as follows

<select name="" ng-model='$parent.fruit' ng-options="fruit as fruit.name for fruit in fruit_list">
  <option value="" selected="selected">Select a fruit</option>
</select>

The $parent.fruit returns null.

Solution

After research, I found out, this creates child scope. So need to use $parent.$parent.fruit instead of $parent.fruit

<select name="" ng-model='$parent.$parent.fruit' ng-options="fruit as fruit.name for fruit in fruit_list">
  <option value="" selected="selected">Select a fruit</option>
</select>

Reference – https://github.com/angular-ui/ui-select/issues/18

Answered By – Ganesh

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.