【问题标题】:ng-model and ng-options not matching up?ng-model 和 ng-options 不匹配?
【发布时间】:2016-02-22 21:58:08
【问题描述】:

我的资源对象中有一个方法:

resources.type

otherstuff: 'more strings'
type:'specifictype'
morestuff: 'morestuff'

用户可以使用下拉列表/通过另一个调用更改此类型,该调用获取所有可能类型的列表,该列表看起来像 resourceList.types,其中包含类似 json 的对象列表

types:
     [
         {name:'resourcetype1'}, 
         {name:'resourcetype2'},
         etc...
     ],

我的 html 看起来像:

<select ng-model="resources.type" ng-options="name.name for name in resourceList.types">
</select>

选择/下拉框填充了我的 resourceList.type 内容,但是当页面加载时,ng-model 未设置为已选择的资源类型。当您单击时,它实际上会在下拉列表顶部选择一个空白条目。角度挑剔吗?如何让 ng-model 以我想要的方式运行?

我尝试使用 ng-options 以不同的方式获得重复,但我觉得这更像是角度连接模型的方式。它只是将字符串与 ng-options 列表匹配吗?

这是 plnkr,你可以看到它没有默认为 type1

http://plnkr.co/edit/NyWACtFQuyndR6CG8lpN?p=info

【问题讨论】:

  • 很抱歉,我无法理解您的架构以及问题所在。你能提供一个 Plunker 来演示这个问题吗?
  • 简单地说,我希望无论 ng-model 是什么,都将下拉菜单默认设置为 ng-options 中 resourceList.types 中的任何字符串。这有意义吗?

标签: angularjs ng-options


【解决方案1】:

在 Angular 中,模型是唯一的事实来源。
这意味着如果您想要选择一个值(并绑定到您的 ngModel),您需要将其分配给模型:

<select ng-model="resources.type"
        ng-options="type.name as type.name for type in resourceList.types">
</select>

$scope.resources = {...};
$scope.resourceList = {
    ...
    types: [
        {name: 'resourcetype1'}, 
        {name: 'resourcetype2'},
        ...
    ]
};

// Set the model to the desired value
$scope.resources.type = $scope.resourceList.types[0].name;

另请参阅此short demo

【讨论】:

  • 是的,我试过了,但它破坏了视图这是 plnkr plnkr.co/edit/NyWACtFQuyndR6CG8lpN?p=info
  • @Garuuk:您的 plunkr 中有一些拼写错误,还需要更改 ngOptions 表达式。看看我更新的答案。
【解决方案2】:

您不必将模型的值设置为 resourceList 中的引用对象。事实上,没有这一行,接受的答案也可以正常工作:

$scope.resources.type = $scope.resourceList.types[0].name;

它是如何工作的?感谢 ngOptions 中的“as”表示法。如果没有“as”,则匹配对象是完整类型元素,因此匹配对象是引用的对象,而不是名称的值。 使用 "as" 匹配元素的属性 name。

我已经分叉了 plunker:http://plnkr.co/edit/kORfxGdsWBUlFWHXp6Ry?p=preview

【讨论】:

    【解决方案3】:

    在我的情况下它不起作用,因为 ngOptions 是一个整数数组,我试图将 ngModal 设置为字符串类型(2014 年 2 月)。

    解决方法很简单:parseInt 函数

    【讨论】:

      猜你喜欢
      • 2016-09-24
      • 1970-01-01
      • 2018-08-29
      • 2023-04-09
      • 1970-01-01
      • 2015-06-30
      • 2015-03-11
      • 2015-05-06
      • 1970-01-01
      相关资源
      最近更新 更多