【问题标题】:Angularjs (select): Show other attribute from array than the one stored in ng-modelAngularjs(选择):显示数组中的其他属性,而不是存储在 ng-model 中的属性
【发布时间】:2014-11-28 17:48:48
【问题描述】:

我有一个选择输入,可以让我在这些对象之间进行选择:

$scope.items = [{"id": "0", "name": "AAA"},
                {"id": "1", "name": "BBB"},
                {"id": "2", "name": "CCC"}]

我需要存储Id并在选择框时显示名称属性,或者当Id已经存储在要修改的对象中时。

对象:

$scope.object

我有这个 html 代码,它将选定的项目 ID 存储在 $scope.object.itemId 中没有问题,但是当它被选中或已经被选中时,选定的项目名称不会显示在选择输入中。

<select ng-model="object.itemId"
        ng-options="item.id as item.name for item in items track by item.id">
</select>

请注意,选择列表已正确填充项目名称。

感谢您的帮助!

【问题讨论】:

  • 删除'track by item.id'

标签: javascript angularjs select angular-ngmodel ng-options


【解决方案1】:

好的,这是我找到的 Angularjs 开发人员最好的解释:https://github.com/angular/angular.js/issues/6564/#issuecomment-51615589

简而言之:您不能将track byselect 结合使用。使用其中一个。

这是上面链接中提供的示例(为方便起见,在此处复制):

有两种不同的用例:

1.您想要一个丑陋的价值的闪亮演示文稿

使用值作为标签:

items = [
  {value: 1, label: 'One'},
  {value: 2, label: 'Two'},
]

template = 'ng-options="item.value as item.label for items"'

当您更改下拉列表时,模型会分配给您在 as 前面定义的任何内容。

2。您想迭代复杂的对象

使用曲目:

items = [
  {id: 1, ...},
  {id: 2, ...},
  {id: 3, ...},
]

template = 'ng-options="item as item.label for items track by items.id"'

当您更改下拉列表时,模型被分配itemtrack by 表达式仅用于通过&lt;option&gt; 上的value 属性将选项与项目相关联

【讨论】:

    【解决方案2】:

    使用 typeahead-input-formatter 并从中返回您希望显示为所选值的值。像这样的

       <select.... typeahead-input-formatter="itemchosen($model)"
    

    然后

        $scope.itemchosen = function(id) {
    
             var theItem = jQuery.grep(items,function(p) { return p.id == id };
             return theItem.name;
    
       };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 2017-08-13
      • 1970-01-01
      • 2019-11-17
      • 1970-01-01
      • 2016-05-02
      • 1970-01-01
      相关资源
      最近更新 更多