简体   繁体   中英

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

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 .

I would highly recommend you name your parent controller. You can do so when defining your controller like

<div ng-controller="parentController as pc">

And then in your code here, you could use the example

<select ng-model="selectedFruit" ng-options="fruit.name for fruit in pc.fruit"></select>

You had a mistake trying to put ng-options on the option tag if you want to use the option tag, you can use an ng-repeat.

<select name="" ng-model="selectedFruit">
  <option ng-repeat="fruit in pc.fruits" value="{{fruit.name}}">{{fruit.name}}</option>
</select>

Here is a good place to find an example, if these don't satisfy your needs: https://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM