Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a json object of arrays that looks like this:

[
    {
        "id": 1,
        "name": "John Smith",
        "age": 52
    },
    {
        "id": 2,
        "name": "Jane Walters",
        "age": 43
    },
    {
        "id": 3,
        "name": "Mike Wilson",
        "age": 65
    },
    {
        "id": 4,
        "name": "Tom Samuels",
        "age": 29
    }
]

I am displaying all these names on the "index" page, and I want to show only one on each of the "character/[id]" pages. Here is my controller for the index page:

angular.module('myApp.controllers', []).
    controller('index', ['$scope', 'characters', function($scope, c){
        $scope.characters = c.getCharacters;
    }]);

Aaand here's the "characters" service:

factory('characters', function($resource){
    return $resource('JSON/characters.json', {}, 
    {
        'getCharacters':    {method: 'GET', isArray:true}
    }); 
});

The views are the standard boilerplate.

My problem is, how do I create a service (or manipulate the object in the controller) for the "character/[id]" route so it only selects a single array based on the JSON id?

I did the phonecat demo on angularjs.org, but that demo uses separate JSON files for each phone, and then one big JSON file for the index page. I want to avoid that.

One final thing: I am using angular-seed, so I'd like to maintain the syntax used there. I've tried lots of different approaches with no luck.

share|improve this question

1 Answer 1

Basically, you are asking how you can get id from the route url.

define your character route path like:

/character/:id

and in your character controller like

....controller('characterCtrl', ['$scope', 'characters','$routeParams' function($scope, c,$params){
    $scope.characters = c.getCharacters;
    //you have $params.id here as the id from the url
}]);

on the commented line loop through the $scope.characters to find the one with matching id and set that to another scope variable. A jsFiddle with your current pages/view and controllers could be more useful while helping.

share|improve this answer
    
I would loop through the array in the controller, but it is empty till loaded in the browser –  symlink Oct 8 '13 at 18:07

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.