Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angularjs

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.

like image 400
user1595465 Avatar asked Aug 13 '12 13:08

user1595465


People also ask

What is location absUrl ()?

$location.absUrl() We can get full url of current web page. $location.url() It returns url without base prefix.

What is $location in AngularJS?

The $location in AngularJS basically uses window. location service. The $location is used to read or change the URL in the browser and it is used to reflect that URL on our page. Any change made in the URL is stored in the $location service in the AngularJS.

What is AngularJS template URL?

templateUrl can also be a function which returns the URL of an HTML template to be loaded and used for the directive. AngularJS will call the templateUrl function with two parameters: the element that the directive was called on, and an attr object associated with that element.


1 Answers

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()}} 
like image 192
pkozlowski.opensource Avatar answered Oct 05 '22 01:10

pkozlowski.opensource