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.