2014-08-27 78 views
1

我想从AngularJS中的一个对象创建一个数组,用于ui-bootstrap的typeahead。 ('蝙蝠侠'),但我需要能够结合几个属性来创建一个新的数组元素('蝙蝠侠(韦恩,布鲁斯))。我可以从一个对象('蝙蝠侠'),但我需要能够结合几个属性来创建一个新的数组元素('蝙蝠侠(韦恩,布鲁斯))。我试过$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 
+0

我会使用'collect' /'map'来代替'pluck',因为它更加规范,IMO。 – 2014-08-27 12:52:02

回答

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

+0

我对lodash相当陌生,不知道有回调......酷,虽然我不知道为什么使用_.map()更好,我改变了使用它...谢谢! – jgravois 2014-08-27 13:21:14

1

尝试使用预输入的 “预输入输入格式器” artribute,你可以将回调传递给它f或格式化最终选定的值