1

I have the following in my controller;

$scope.location = $location.absUrl();

This gives me the full URL of the current page being viewed. In my HTML I would like to apply a class if the URL contains a certain parameter.

ng-class="{'location': location == }

I'm not really sure what to put after the : to evaluate the expression. a url may include a string such as 'requestId=555'

How can I write an expression so that if a URL includes that string the class then gets applied?

Flignats
  • 1,234
  • 10
  • 21

1 Answers1

1

If you are using ui-router

You can have a state param for the query string. If you inject $stateParams into your controller, you can access set $scope.requestId = $stateParams.requestId. In your view, you can then bind to requestId. To set up the state:

$stateProvider.state({
    url: '/someurl?requestId',
    templateUrl: 'someTemplate.tpl.html',
    controller: 'SomeController'
});

See ui-router.

If you want plain vanilla js

According to this highly accepted answer, you can get the query string value of a key with the following function:

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

You can then set $scope.requestId = getParameterByName('requestId'); and bind to it in your template.

Community
  • 1
  • 1
Seth Flowers
  • 8,990
  • 2
  • 29
  • 42
  • Unfortunately, I am not using ui-router in the application. – Flignats Dec 03 '15 at 19:27
  • I needed to make a small adjustment to bring it into an angular controller: $scope.getParameterByName = function (name) { name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); var regex = new RegExp("[\\?&]" + name + "=([^]*)"), results = regex.exec(location.search); return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); }; – Flignats Dec 04 '15 at 00:12