pes502 pes502 - 6 months ago 17
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"
};

$scope.cars[] = {
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 = users.id
. I tried something like this:

<div class="...">{{ users.name | filter: {users.id:cars.userid} }}</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

Simple.

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;
    }
});

HTML

<!-- users come from $scope.users -->
<div>The user of {{ cars[0].name }} is {{ cars[0].userId | carUser:users }}</div>