2

I am trying to create an array from an object in AngularJS to use for ui-bootstrap's typeahead.

I am able to pluck a single value out of the object ('Batman') but I need to be able to combine several properties to create a new array element ('Batman (Wayne, Bruce)). I tried $scope.heroList = _.pluck($scope.heroes, 'name' + '(' + 'lname' + ', ' + 'fname' + ')' ); but got all nulls.

Here is a plunker.

I need a final array that looks like this:

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

Here is my 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
Satpal
  • 132,252
  • 13
  • 159
  • 168
jgravois
  • 2,559
  • 8
  • 44
  • 65

2 Answers2

3

You can use callback method.

Use

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

DEMO

Also I would recommend you to use _.map()

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

DEMO with map

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Try using typeahead's "typeahead-input-formatter" artribute, you can pass a callback to it for formatting the final selected value

Coder John
  • 776
  • 4
  • 7