【问题标题】:How to use ng-options with ng-model to bind with parent scope variable?如何使用 ng-options 和 ng-model 来绑定父范围变量?
【发布时间】:2018-03-30 05:30:16
【问题描述】:

我正在使用 AngularJS 和 UI 路由器。我有一个父母状态和一个孩子。父状态包含一个初始化为null 的变量。在子状态下,我显示了一个下拉列表,如下所示

<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 返回null

【问题讨论】:

  • 分享父状态码,你在嵌套循环吗?

标签: javascript angularjs angular-ui-router


【解决方案1】:

我强烈建议您命名您的父控制器。您可以在定义控制器时这样做

<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/

【讨论】:

    【解决方案2】:

    经过研究,我发现这会创建子范围。所以需要使用$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>
    

    参考 - https://github.com/angular-ui/ui-select/issues/18

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 2015-06-30
      • 1970-01-01
      • 2015-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多