有没有办法在$ routeProvider中添加额外的参数并在指令中检索这些参数?我需要这个,因为变量是特定于页面的。
我想在routeprovider中添加一个参数pageName,如下所示:
$routeProvider
.when('/home',
{
controller: 'homeController',
templateUrl: '_templates/home.html',
pageName: 'home'
})
并在指令中使用此额外参数
directives.dirPagename = ['$route', '$routeParams', function($route, $routeParams) {
return {
restrict: 'ECA',
template: 'test',
link: function (scope, elem, attrs) {
console.log($route);
console.log($routeParams);
}
}
}]
当我记录$ route并在google webdeveloper工具中检查时,pageName参数有几层深。
Object {routes: Object, reload: function}
current: D
$$route: Object
controller: "homeController"
**pageName: "home"**
有没有办法直接获取此变量,或者这完全是错误的方法?
更新:
您可以在路由中获取变量 var pageName = $ route.routes [$ location。$$ path] .pageName;
答案 0 :(得分:2)
您可以在$ route.routes [uri]中找到相关信息。
我与你分享我的viewRouter服务作为例子:
var uaViewRouter = angular.module('ua.ViewRouter', []);
uaViewRouter.service('uaViewProvider', function($route, $location, uaContext){
this.redirectToView = function(viewName){
url = undefined;
for(var route in $route.routes){
if ($route.routes[route].view == viewName){
url = route;
}
}
if(url == undefined){
throw("uaViewProvider: Undefined view " + viewName);
}
if($route.routes[url].enrichment == true){
url = url.replace(":operatorId", uaContext.operator.get().id);
url = url.replace(":productId", uaContext.product.get().id);
}
$location.path(url);
};
});
uaViewRouter.run(function($rootScope, uaViewProvider) {
$rootScope.uaViewProvider = {};
$rootScope.uaViewProvider.redirectToView = function(viewName) {
uaViewProvider.redirectToView(viewName);
};
});
路线声明的例子:
uaApp.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'app/login/login.tpl.html',
loginRequired: false,
view: 'login'
}).
...
您可以通过以下方式在控制器或服务中使用它:
uaViewProvider.redirectToView('login');
或在模板中:
<a href="" ng-click="uaViewProvider.redirectToView('login')">Click to login</a>