【问题标题】:angularjs ng-options select as custom object from the options arrayangularjs ng-options 从选项数组中选择为自定义对象
【发布时间】:2014-09-29 20:09:16
【问题描述】:

我正在尝试从 ng-options 对象列表中获取 2 个不同的 id,并将其映射到用户选择的选择模型中。模型已正确映射,但值未显示在选择框上。

http://plnkr.co/edit/Z3ohLie4vpTvXhUiLfl6?p=preview

<!DOCTYPE html>
    <html ng-app="angularjs-starter">

      <head lang="en">
        <meta charset="utf-8">
        <title>Custom Plunker</title>
        <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
        <link rel="stylesheet" href="style.css">
        <script src="app.js"></script>
      </head>

      <body ng-controller="MainCtrl">
        <h1>Select something</h1>
        <select ng-model="selectedItem" ng-options="{'id':item.id,'anotherid':item.anotherId} as item.name for item in items"></select>
        <h3>The selected item:</h3>
        <pre>{{selectedItem | json}}</pre>
      </body>

    </html>

Javascript:

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.items = [
    { id: 1, name: 'foo', anotherId: 11 },
    { id: 2, name: 'bar', anotherId: 22 },
    { id: 3, name: 'blah', anotherId: 33 }];
});

【问题讨论】:

    标签: angularjs ng-options


    【解决方案1】:

    您使用的是非常旧的 Angular 版本。如果您可以使用相当新的版本,答案是使用ng-optionstrack by 子句:

    <select ng-model="selectedItem"
      ng-options="{'id':item.id,'anotherid':item.anotherId} as item.name for item in items track by item.id"></select>
    

    分叉的 plunk:http://plnkr.co/edit/0SwHfYVuYd5iIA9P4mpU?p=preview

    【讨论】:

    • 我真的不明白为什么简单的选择这么复杂。无论如何+1以获得正确答案,但我会尝试找出更简单的解决方案:)
    • 我同意选择中的理解内容过于复杂且解释不足。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-29
    • 2014-07-26
    • 1970-01-01
    • 2015-11-04
    • 2019-01-08
    • 2017-12-31
    相关资源
    最近更新 更多