0

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.

2
  • An now, you want to use filter for it? Commented May 27, 2016 at 14:06
  • I think, that is faster then write X separately functions ... bcs I need to merge data between Y arrays :/ Commented May 27, 2016 at 14:08

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

it looks good, but how can I define the array in the filter? In your example I see error "users not defined"
@pes502 See edit. You just pass users in with carUser:users. Then in your filter implementation, the first argument is always the input. Subsequent arguments are what you pass in: filterName:arg1:arg2:arg3:etc....
thank you man, I edited your code a little bit and its working as I expected and this is what I need :) btw your nick is too OP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.