pes502 pes502 - 2 years ago 202
AngularJS Question

How to display array element by expression

I am using AngularJS and in my controller I have some arrays, for example:

$scope.users[] = {
id: 0,
name: "John",
surname: "Doe"

$[] = {
id: 0,
userid: 0,
color: "blue"

then in view, I want to display some data, for example:

<div class="...">{{ cars[0].color }}</div>

this working fine. But now, I want to display name of the users,
where cars.userid =
. I tried something like this:

<div class="...">{{ | filter: {} }}</div>

but it throws an error of course. I am not sure, if I can use filters this way, or if I must write my own function to the controller, which return the right user name, something like:

$scope.showUserName = function(id) {
for(var i = 0; i < $scope.users.length; i++) {
if(id == $scope.users[i].id) {
return $scope.users[i].name;

and then in my view:

<div class="...">{{ showUserName(cars.userid) }}</div>

Thank you for explanation.

Answer Source


First, define your filter like this

app.filter('carUser', function() {  //register the filter
    return function(carId, users) { //first arg = input, subsequent argument = others
        for(var key in users)
            if(users[key].id === carId)
                return users[key].name;


<!-- users come from $scope.users -->
<div>The user of {{ cars[0].name }} is {{ cars[0].userId | carUser:users }}</div>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download