AngularJS: how can I get $location.path to template

Angularjs

Angularjs Problem Overview


I need current path from url in template (content of $location.path). But not via controller, because I have a lot of controllers (and I do not want to duplicate declaration of $scope.currentUrl = $location.path;). Thanks for the advice.

Angularjs Solutions


Solution 1 - Angularjs

AngularJS template can only see what is available in a scope so you will need somehow to put $location service in a scope. There is one scope that is always available in AngularJS application called $rootScope so it could be use for your use-case.

What you could do is to use run() method of a module to expose $location in the $rootScope:

var myApp = angular.module('myApp', []).run(function($rootScope, $location) {
    $rootScope.location = $location;
});

this would make 'location' available in all templates so later on you could do in your template:

Current path: {{location.path()}}

Solution 2 - Angularjs

An alternative is to use the more semantic and versatile ui-router, then in the controller, retrieve the current state, and store it on the $scope:

app.controller('MyCtrl', ['$scope', '$state', function MyCtrl($scope, $state) {
  $scope.state = $state.current.name;
  ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1595465View Question on Stackoverflow
Solution 1 - Angularjspkozlowski.opensourceView Answer on Stackoverflow
Solution 2 - AngularjsDan DascalescuView Answer on Stackoverflow