如何使用 ng-options 和 ng-model 来绑定 parent 范围变量?
How to use ng-options with ng-model to bind with parent scope variable?
我正在使用 AngularJS 和 UI-router。我有一个 parent 状态和一个 child。 parent 状态包含一个初始化为 null
的变量。在 child 状态下,我显示了如下下拉列表
<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>
$parent.fruit
returns null
.
我强烈建议您命名您的父控制器。你可以在定义你的控制器时这样做
<div ng-controller="parentController as pc">
然后在此处的代码中,您可以使用示例
<select ng-model="selectedFruit" ng-options="fruit.name for fruit in pc.fruit"></select>
你在尝试将 ng-options 放在选项标签上时出错了如果你想使用选项标签,你可以使用 ng-repeat.
<select name="" ng-model="selectedFruit">
<option ng-repeat="fruit in pc.fruits" value="{{fruit.name}}">{{fruit.name}}</option>
</select>
这里是查找示例的好地方,如果这些不能满足您的需求:https://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
经过研究,我发现,这会创建子作用域。所以需要使用 $parent.$parent.fruit
而不是 $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>
我正在使用 AngularJS 和 UI-router。我有一个 parent 状态和一个 child。 parent 状态包含一个初始化为 null
的变量。在 child 状态下,我显示了如下下拉列表
<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>
$parent.fruit
returns null
.
我强烈建议您命名您的父控制器。你可以在定义你的控制器时这样做
<div ng-controller="parentController as pc">
然后在此处的代码中,您可以使用示例
<select ng-model="selectedFruit" ng-options="fruit.name for fruit in pc.fruit"></select>
你在尝试将 ng-options 放在选项标签上时出错了如果你想使用选项标签,你可以使用 ng-repeat.
<select name="" ng-model="selectedFruit">
<option ng-repeat="fruit in pc.fruits" value="{{fruit.name}}">{{fruit.name}}</option>
</select>
这里是查找示例的好地方,如果这些不能满足您的需求:https://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
经过研究,我发现,这会创建子作用域。所以需要使用 $parent.$parent.fruit
而不是 $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>