采摘多个属性

时间:2014-08-27 12:45:35

标签: javascript angularjs lodash

我正在尝试从AngularJS中的对象创建一个数组,以用于ui-bootstrap的typeahead。

我能够从对象中取出一个值('蝙蝠侠'),但我需要能够组合几个属性来创建一个新的数组元素('蝙蝠侠(Wayne,Bruce))。我尝试了$scope.heroList = _.pluck($scope.heroes, 'name' + '(' + 'lname' + ', ' + 'fname' + ')' );,但得到了所有空值。

这是plunker

我需要一个如下所示的最终数组:

$scope.heroList = ['Batman (Wayne, Bruce]', 'Daredevil (Murdoch, Jack'), ... ];

这是我的javascript:

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

app.controller('MainController', function($scope){

  $scope.heroes = [
    {
      id: 1,
      name: 'Iron Man',
      fname: 'Tony',
      lname: 'Stark',
      location: 'Stark Tower',
      comic: 'Marvel'
    },
    {
      id: 2,
      name: 'Batman',
      fname: 'Bruce',
      lname: 'Wayne',
      location: 'Bat Cave',
      comic: 'DC'
    },
    {
      id: 3,
      name: 'Superman',
      fname: 'Clark',
      lname: 'Kent',
      location: 'Metroplis',
      comic: 'DC'
    },
    {
      id: 1,
      name: 'Daredevil',
      fname: 'Jack',
      lname: 'Murdock',
      location: 'Court Room',
      comic: 'Marvel'
    },
    {
      id: 5,
      name: 'Flash',
      fname: 'Barry',
      lname: 'Allen',
      location: 'Speedline',
      comic: 'DC'
    },
    {
      id: 6,
      name: 'Hulk',
      fname: 'Bruce',
      lname: 'Banner',
      location: 'Labratory',
      comic: 'Marvel'
    },
    {
      id: 7,
      name: 'Hawkeye',
      fname: 'Clint',
      lname: 'Barton',
      location: 'Nest',
      comic: 'Marvel'
    },
    {
      id: 8,
      name: 'Thor',
      fname: 'Donald',
      lname: 'Blake',
      location: 'Asgard',
      comic: 'Marvel'
    }
  ];

  $scope.heroList = _.pluck($scope.heroes, 'name');
  //$scope.heroList = _.pluck($scope.heroes, 'name' + '(' + 'lname' + ', ' + 'fname' + ')' );

}); // end MainController

2 个答案:

答案 0 :(得分:3)

您可以使用回调方法。

使用

$scope.heroList = _.pluck($scope.heroes, function(elm){
    return elm.name + '(' + elm.lname + ', ' + elm.fname + ')';
});

DEMO

我还建议您使用_.map()

$scope.heroList = _.map($scope.heroes, function(elm){
    return elm.name + '(' + elm.lname + ', ' + elm.fname + ')';
});

DEMO with map

答案 1 :(得分:1)

尝试使用typeahead" typeahead-input-formatter" artribute,您可以将回调传递给它以格式化最终选定的值