1

I have a drop down that changes the ID of a value. The value corresponds to the JSON object.

I'm having problems "searching" or "filtering" the JSON objects name(property) by using the ID.

Code for displaying the current station

<a class="navbar-brand" href="#">{{ stations.name | station_id:2 }}</a>

Current stations

$scope.currentStation = 1;
//Fake data
$scope.stations = 
[
    {'name':'Station1', 'station_id':1,'featured_album':'1 Featured Album'},
    {'name':'Station2', 'station_id':2,'featured_album':'2 Featured Album'},
    {'name':'Station3', 'station_id':3,'featured_album':'3 Featured Album'}
];

1 Answer 1

3

First of all a filter is used to filter a collection and return the modified collection.

<div ng-repeat="station in stations | getById('2')">
    <a class="navbar-brand" href="#">{{ stations.name }}</a>
</div>

You can then create a filter that get this value based on the Id. But that's not what you want, since you're not using an ng-repeat. You just want to get a single value out of your collection. I suggest you to create a function in your controller that does this job for you:

$scope.getStationById = function(id) {
    var parsedId = +id,
        foundStation;

    angular.forEach($scope.stations, function(station) {
        if(station.station_id === parsedId) {
            foundStation = station;
        }
    });

    return foundStation;
};

jsFiddle

or you can use the currentstation scope variable:

jsFiddle - update

Edit: Maybe I'm wrong, if you want to show more than just the name, it's a good advice to avoid multiple iterations on the controller. With a filter you can limit this to one iteration. Your filter should give back a new collection with only one result:

app.filter('getById', function() {
        return function(coll, id) {
            var parsedId = +id,
                foundStation;

            angular.forEach(coll, function(station) {
                if(station.station_id === parsedId) {
                    foundStation = station;
                }
            });

            // Create array if station found otherwise return empty array
            return foundStation ? [foundStation] : [];        
        };
    });

JsFiddle

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

1 Comment

a filter is used to filter a collection - No. Only the built-in filter filter operates on collections.

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.