【发布时间】:2012-08-13 13:27:20
【问题描述】:
我需要模板中 url 的当前路径($location.path 的内容)。但不是通过控制器,因为我有很多控制器(而且我不想重复声明$scope.currentUrl = $location.path;)。谢谢你的建议。
【问题讨论】:
标签: angularjs
我需要模板中 url 的当前路径($location.path 的内容)。但不是通过控制器,因为我有很多控制器(而且我不想重复声明$scope.currentUrl = $location.path;)。谢谢你的建议。
【问题讨论】:
标签: angularjs
AngularJS 模板只能查看范围内可用的内容,因此您需要以某种方式将 $location 服务放入范围内。 AngularJS 应用程序中有一个始终可用的范围,称为 $rootScope,因此它可以用于您的用例。
您可以做的是使用模块的 run() 方法在 $rootScope 中公开 $location:
var myApp = angular.module('myApp', []).run(function($rootScope, $location) {
$rootScope.location = $location;
});
这将使“位置”在所有模板中都可用,以便稍后您可以在模板中执行:
Current path: {{location.path()}}
【讨论】:
Current path: {{$parent.location.path()}}
{{ $root.location.xxx }} 是一个好习惯,因为任何具有隔离范围的指令都无法通过速记方法访问它,并且$parent.location 不可靠,具体取决于您的范围深度。 $root 始终有效。
另一种方法是使用更语义化和通用的ui-router,然后在控制器中retrieve the current state,并将其存储在$scope上:
app.controller('MyCtrl', ['$scope', '$state', function MyCtrl($scope, $state) {
$scope.state = $state.current.name;
...
}
【讨论】:
$state.href($state.current),而不是$state.current.name。