0

I am having trouble trying to get Angular to spit out the url of the page in to the page class each time the navigation changes the page. This is what I have so far:

$scope.currentPage = getCurrentPage;

  var getCurrentPage = function () {
    var login = 'login';
    var url = $location.url().substring(1);
    if (url = null || url = undefined) {
      return login;
    } else {
      return url;
    }
  };

I have this on the content wrapping <div>:

<div class="" ng-controller="AppCtrl" ng-class="currentPage + 'Page'"></div>

Any hardcore Angulars out there? Please help.

JP

JohnRobertPett
  • 1,133
  • 4
  • 21
  • 36

2 Answers2

0

A few things to do differently:

I don't think the function is actually getting called, so:

$scope.currentPage = getCurrentPage();
$scope.currentPage += "Page"; // just keeping the concatenation out of the markup

EDIT: I think I'm wrong about the above statement. I'm still fuzzy on when to call() vs reference the function in situations like this...

Also, this line needs some retouching of the operators:

if (url == null || url === undefined);

And, I am not sure ng-class is entirely necessary in this case. It is usually used to evaluate an expression. I would simply use:

<div class="" ng-controller="AppCtrl" class="{{currentPage}}"></div>

Hopefully someone else can verify me on all of these points, as I am fairly new to JS and AngularJS.

rGil
  • 3,719
  • 1
  • 22
  • 30
  • Ah, i was totally wrong on the operators, though I seem to get that returned as 'undefined' now! – JohnRobertPett Apr 29 '13 at 14:49
  • Also, be sure to place the function call (line 1) AFTER the function definition. IOW, move line one to the bottom. – rGil Apr 29 '13 at 15:22
  • One more tricky part - you should wrap this in a $watch, or the function will run only once on page load, and currentPage won't update with a new url. [This post](http://stackoverflow.com/questions/11555181/angularjs-update-model-based-on-url) may help. – rGil Apr 29 '13 at 15:24
  • Right, after a bit of tweaking of your wonderful guidance I now have it working! Thanks to you both! – JohnRobertPett Apr 29 '13 at 15:54
0

For anyone who comes across this and would like a more verbose answer, here you go!

In view:

<div class="" ng-controller="AppCtrl" class="currentPage"></div>

In controller:

  $scope.$watch(function () {return $location.url();}, function () {

    var getCurrentPage = function () {
      var login = 'loginPage';
      var currentUrl = $location.url().substring(1);
      if (currentUrl === '' || currentUrl === undefined) {
        return login;
      } else {
        return currentUrl + 'Page';
      }
    };

    $scope.currentPage = getCurrentPage();

    console.log($scope.currentPage);

  });
JohnRobertPett
  • 1,133
  • 4
  • 21
  • 36