AngularJS将多个对象添加到对象文字

时间:2015-07-10 21:00:21

标签: javascript angularjs object

当我点击" Evan"我明白了:

{"id":1,"name":"Evan"}

当我点击" Robert"我明白了:

{"id":2,"name":"Robert"}

如何修改此代码以遵循上述步骤并获取此类对象(不是数组):

{"id":1,"name":"Evan"},
{"id":2,"name":"Robert"}

这是我的Plunker: http://plnkr.co/edit/EkKlx7cJG8L0IkRTY6dU?p=preview

以下是我的观点:

  <body ng-controller="MainCtrl">
    <ul>
      <li ng-repeat="item in items" ng-click="select(item)">
        {{item.name}}
      </li>
    </ul>
    <p ng-show="selected">{{selected}}</p>
  </body>

这是我的控制人员:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
    $scope.items = {
        "1": {
            "id": 1,
            "name": "Evan"

        },
        "2": {
            "id": 2,
            "name": "Robert"

        },
        "3": {
            "id": 3,
            "name": "Justin"
        }
    }
  $scope.selected = {};
    $scope.select = function (item) {
    $scope.selected = item;
    }
});

1 个答案:

答案 0 :(得分:1)

您需要为selected对象中的预期值提供密钥。

如果您反对数组,我建议您修改select函数:

$scope.select = function (item) {
  $scope.selected[item.id] = item;
};

plunker