Stian Bakken
Stian Bakken

Reputation: 673

Routing in angular with subpages

I have an Angular page where I ng-repeat through a projectlist (json).

ng-repeat="project in projects"

It's structured like this:

[{"number":789456,"title":"Coolest project ever","manager":"Darth Vader","image":7,"startdate":"25.1.2013","enddate":"8.7.2015","location":"Deathstar","favorited":"not"}]

So, I've made each ng-repeat have the following:

<a ng-href="#/projects/{{project.number}}"></a>

I've set up the route the following way:

 .when('/projects', {
        templateUrl: '/views/projects.html',
        controller: 'ProjectController',
        controllerAs: 'pr',
        title: 'Prosjekter'
    })

    .when('/projects/:projectNumber', {
        templateUrl: '/views/projectdetails.html',
        controller: 'ProjectController',
        controllerAs: 'pr',
        title: 'Prosjekt'
    })

My controller looks like this:

var app = angular.module('app');

app.controller('ProjectController', function($scope, projectList, $mdDialog, $q, $timeout, $routeParams){

  $scope.projectNumber = $routeParams.projectNumber;
  $scope.projects = projectList.query();


  $scope.project = $scope.projects.filter(function(project) {
        return project.number === $routeParams.projectNumber;
    })[0];

I get the projectlist from my factory called "projectList".

My problem is, the view loads up correctly, but I have no way of accessing the variables of the project once I'm in this 'child-view' of projects.

I tried using {{project.number}}, but it doesn't work. How would I define this in my controller?

Upvotes: 1

Views: 1282

Answers (2)

varun
varun

Reputation: 662

Can you check the type of $routeParams.projectNumber. Is it a string or a number?

Try this in the controller

$scope.project = $scope.projects.filter(function(project) {
    return project.number == $routeParams.projectNumber;
})[0];

Upvotes: 0

ccjmne
ccjmne

Reputation: 9618

In your ProjectController, you need to use $routeParams in order to refer to your projectNumber defined in the url.

{{project.number}} won't be available until you've defined $scope.project. When you need to refer to the project number obtained from the url, use $routeParams.projectNumber.

For example, you'd have:

app.controller('ProjectController', ['$scope', '$routeParams', function ($scope, $routeParams) {
    var projects = [{...}, ...];
    $scope.project = projects.filter(function(project) {
        return project.number === $routeParams.projectNumber;
    })[0];
}]);

Upvotes: 1

Related Questions