1

I've added this to my side navigation's controller:

if($location.path() == '/goals') {
    $scope.goals_active = true;
}

This works perfectly fine and applies the active class with ng-class.

However, the problem I am now running into is with an id.

i.e. /goals/b2dcf461-56f6-f812-bed0-538e1603a595

How can I tell my application, in Angular (and using $location if necessary), to not only set $scope.goals_active to true when the path is /goals, but also /goals/:id?

I need some kind of a * operator but don't know how this is possible.

asgwar12
  • 131
  • 1
  • 9

4 Answers4

1

Just use a Regex:

/\/goals(\/.*)?/.test($location.path());

Here is a quick snippet showing the test code in action:

var urls = ['/goals', '/goals/', '/goals/12345'];

urls.forEach(function(url){
  var matches = /\/goals(\/.*)?/.test(url);
  
  document.write("url: " + url + "  [" + matches + "]");
  document.write("<br />");
});
Josh
  • 44,706
  • 7
  • 102
  • 124
0
     if($location.path().indexOf("/goals") >= 0)

should match anything with /goals in it.

Scott
  • 1,690
  • 3
  • 13
  • 18
0

If you don't think you'll have URLs like /goalsSomething which should not be triggered, you can simply do:

if($location.path().match('/goals')) {
    $scope.goals_active = true;
}

Or what Scott suggested.

Shomz
  • 37,421
  • 4
  • 57
  • 85
0

Your safest route is probably to use a regular expression:

if( /\/goals(\/.*)?/.test($location.path()) ) { $scope.goals_active = true; }

You can also use indexOf, but that begins to get more complicated when you experience routes with additional text like '/goalsasdf'. There are also a number of other ways to do this, with increasing complexity.

Community
  • 1
  • 1
Bobby
  • 1,439
  • 2
  • 16
  • 30