title: Angular js: How to use URL path in a controller to populate scope
body: <p>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. </p>
  
  <p>If I use console.log to check what's in $scope.pageDetail.id withing the <em>for</em> loop, I get the correct response, but it returns "undefined" outside of the <em>for</em> loop. Everything works on page reload, but not when I use the page's navigation to click my way through the urls.</p>
  
  <p><strong>My controller:</strong></p>
  
  <pre><code>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 &lt; data.length; i++) {
        if (data[i].id === pageId) {
          $scope.pageDetail = data[i];
          break;
        }
      }
    });
  
  })
  </code></pre>
  
  <p><strong>My service</strong></p>
  
  <pre><code>oddproto.factory('PageService', function($resource) {
    return $resource('includes/pages.json');
  });
  </code></pre>
  
  <p><strong>pages.json</strong></p>
  
  <pre><code>[
    {
      "id": "blog",
      "name": "Blogg"
    },
    {
      "id": "cases",
      "name": "Projekt"
    },
    {
      "id": "contact",
      "name": "Kontakt"
    }
  ]
  </code></pre>
  
  <p><strong>I've also tried doing this entirely without the service, i.e.</strong> </p>
  
  <pre><code>$scope.pageDetail = $location.path().replace("/", "");
  </code></pre>
  
  <p>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.</p>