【问题标题】:AngularJS Select Options PreselectionAngularJS 选择选项预选
【发布时间】:2018-06-12 06:28:44
【问题描述】:

我在 angularJS 中预选选择输入时遇到了一些问题。 选择框被一个数组填充。

<select class="form-control" 
ng-model="userCtrl.selected_country" 
ng-options="country.name for country in userCtrl.available_countries track by country.id">
</select>

例如一个选定的国家/地区填充了一个 ID(我通过 API 获得)。

userCtrl.selected_country = 4;

但这行不通。我也尝试过使用 options 和 ng-selected 来做到这一点。

<option ng-repeat="country in userCtrl.available_countries"
ng-selected="{{ country.id == userCtrl.selected_country }}"
value="{{ country.id }}">
{{ country.name }}
</option>

为什么我不能这样选择?这“有效”,在源代码中我看到正确的选项 selected="true" - 但在视图中你看不到它......非常奇怪。

我现在的“解决方案”是,用源数组“available_countries”的正确值填充我的 ng 模型。 不必要的许多步骤?!

  1. API 的加载数据(选择填充)
  2. 加载 API 的数据(地址)
  3. 将所有引用 ID(如 country_id、state_id)操作到 select-fill-objects(用于预选)
  4. 发生用户编辑 => 用户点击更新
  5. 将所有 select-fill-objects 改回 reference-id
  6. 立即保存地址
  7. 重复第 3 步

如果我可以仅使用数字进行预选,则不需要 3.、5. 和 7.。 这有可能吗?

感谢您的帮助 :-) 斯蒂芬

【问题讨论】:

标签: javascript angularjs angularjs-select


【解决方案1】:

稍微扩展@zeroglagL 的答案。

在您的示例中,ng-options 指令的使用方式告诉 AngularJS ng-modeloption 应该是具有相同结构的对象:

// JSON representation of userCtrl.selected_country is an object
{
    name: "Poland",
    id: 1 
}

// JSON representation of userCtrl.available_countries in an array of objects
[
{
    name: "Poland",
    id: 1 
}
{
    name: "USA",
    id: 2
}
]

所以基本上当你使用时:

ng-options="country.name for country in userCtrl.available_countries track by country.id"

您告诉 AngularJS 为 userCtrl.available_countries 数组中的每个 country 创建选项对象,country.name 作为标签,country.id 作为每个选项的值。 AngularJS 还将假定 ng-model 将成为一个对象,并将通过两个对象的 id 属性将选项与模型“绑定”。

所以你必须按照我上面描述的方式构建你的ng-model

或者您可以以其他方式使用ng-options(如@zeroglagL 所述):

ng-options="country.id as country.name for country in userCtrl.available_countries"

在这种方法中,您告诉 AngularJS 仅将选项和 ng-model 视为标量 ids(而不是对象)。不再需要通过 ids 来“绑定”对象,因为 AngularJS 在预选选项时会简单地比较整数值。这样userCtrl.available_countries实际上可以是对象数组,但ng-model值(在选择或预选之后)将只包含id

【讨论】:

    【解决方案2】:

    模型必须匹配选项的值。在您的情况下,模型是一个 id,而选项值是整个对象。

    要么将模型也设为对象,要么这样做

    ng-options="country.id as country.name for country in userCtrl.available_countries"
    

    【讨论】:

      【解决方案3】:

      要使其工作,您必须将ng-model 绑定到您要选择的对象,而不是id。所以,试试这个:

      $scope.userCtrl.selected_country = $scope.userCtrl.available_countries[4];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-12
        • 2015-04-09
        • 2013-09-16
        • 2016-09-03
        • 2021-03-14
        • 2016-11-16
        • 2013-03-26
        相关资源
        最近更新 更多