AngularJS:如何获取模板的$ location.path [英] AngularJS: how can I get $location.path to template
问题描述
我需要模板中url的当前路径($ location.path的内容).但是不能通过控制器,因为我有很多控制器(并且我不想重复$scope.currentUrl = $location.path;
的声明).感谢您的建议.
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模板只能看到作用域中可用的内容,因此您将需要以某种方式将$ location服务放入作用域中. AngularJS应用程序中始终有一个名为$ rootScope的作用域,因此可以用于您的用例.
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.
您可以做的是使用模块的run()方法在$ rootScope中公开$ location:
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()}}
这篇关于AngularJS:如何获取模板的$ location.path的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!