0

I'm having two array in my scope: employees and cars. Every employee has a carId which matches a car out of the cars-array.

Employee looks like

[{'id': 1, 'name': 'John', 'carId': 1}]

Car like

[{'id': 1, 'color': 'red'}]

Now I have an ng-repeat and would like to output the color of the car directly with an filter:

{{ employee.carId | selectFromCars:$scope.cars }}

I don't know how to get access to the cars array inside the filter. Is this even possible or should I inject the car into the employee after loading and then just use following?

{{ employee.car.color }}
4
  • Can you provide JSFiddle link of your issue? Commented Mar 9, 2017 at 2:16
  • Here is one jsfiddle.net/3tq83xkL/2 Commented Mar 9, 2017 at 2:31
  • 1
    I've updated your JSFiddle link. Have a look. I've not used filter instead called function and interpolated it's response. Commented Mar 9, 2017 at 2:50
  • It works thank you. Bit easier than a filter, but less reusable unfortunately. Commented Mar 9, 2017 at 3:00

1 Answer 1

1

you can make your own custom filter and just add it the end of your controller like so:

.filter('empCarFilter', function() {

    return function(carId, cars) {

        // you can access $scope.cars here, for example...

        angular.forEach(cars,function(value){
            if (value.id === carId) {
                 return value.color;
             } 
             // etc...etc...
        })

}

The above method is under the assumption that you are passing employee.carId into the filter. But, not sure how useful this would be for you, but you can pass the whole object to the filter as well and not just one key with:

 {{ employee | empCarFilter }}

Here is also a pretty good reference for custom filters: https://scotch.io/tutorials/building-custom-angularjs-filters

Sign up to request clarification or add additional context in comments.

1 Comment

How do I get access to the $scope. There is no possibility to inject?

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.