AngularJS: how can I get $ location.path for a template

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

+48
angularjs
Aug 13 2018-12-12T00:
source share
2 answers

The AngularJS template can only see what is available in the area, so you need to somehow put $ location service in the area. There is one area that is always available in an AngularJS application called $ rootScope, so it can be used for your use case.

What you can do is use the run () method of the module to output $ location to $ rootScope:

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

this would make the "location" available in all templates so that later you can do in your template:

 Current path: {{location.path()}} 
+87
Aug 13 2018-12-12T00:
source share
— -

An alternative is to use a more semantic and universal ui-router , then in the controller get the current state and save it on $scope :

 app.controller('MyCtrl', ['$scope', '$state', function MyCtrl($scope, $state) { $scope.state = $state.current.name; ... } 
0
Oct 24 '14 at 18:08
source share



All Articles