Adam Gerthel
Adam Gerthel

Reputation: 692

Angular js: How to use URL path in a controller to populate scope

I want to be able to use part of the URL in a controller, in this case to be able to set a body class based on the URL, but I would also like to use a service to fetch other information from a json file based on that URL.

If I use console.log to check what's in $scope.pageDetail.id withing the for loop, I get the correct response, but it returns "undefined" outside of the for loop. Everything works on page reload, but not when I use the page's navigation to click my way through the urls.

My controller:

oddproto.controller('UrlController', function($scope, $location, PageService){

  // Get page id from URL
  var pageId  = $location.path().replace("/", "");

  $scope.pageDetail = PageService.query(function(data) {
    // Get the correct page details from the dataset
    for (var i = 0; i < data.length; i++) {
      if (data[i].id === pageId) {
        $scope.pageDetail = data[i];
        break;
      }
    }
  });

})

My service

oddproto.factory('PageService', function($resource) {
  return $resource('includes/pages.json');
});

pages.json

[
  {
    "id": "blog",
    "name": "Blogg"
  },
  {
    "id": "cases",
    "name": "Projekt"
  },
  {
    "id": "contact",
    "name": "Kontakt"
  }
]

I've also tried doing this entirely without the service, i.e.

$scope.pageDetail = $location.path().replace("/", "");

But that only works on page load as well, so it seems to me like $location is the issue here. I don't know what else I can use though.

Upvotes: 2

Views: 15365

Answers (2)

kfis
kfis

Reputation: 4729

Your controller is not recognizing the location change. When the controller is initialized, it sets the page id, but after changing, your controller is not re-initialized. For this, you should use

scope.location=$location;
scope.$watch('location.path()', function(path) {
  $scope.pageDetail = ....
});

This will observe location.path() and if its changing, it does your custom magic.

Furthermore, I suggest you to make your controller to be a directive, as it is only dealing with styling your body-tag.

Upvotes: 4

Adam Gerthel
Adam Gerthel

Reputation: 692

I got it working using $routeChangeSuccess

  $scope.$on('$routeChangeSuccess', function() {
    $scope.pageId = $location.path().replace("/", "");
  })

There might be an issue in angular using $watch for in regards to $location

Upvotes: 1

Related Questions