我遇到了一点挑战,还没有找到解决方案。当我尝试了一些事情时,我正在请求你的帮助,所以可能有人可以引导我走向正确的方向。
我在 AngularJS 中有一个 routes.js。我正在使用 $routeProvider
。在每个 .when()
中,我需要调用一个函数(因为我需要对名称做一些事情)。
$routeProvider
.when('/url', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url1', { templateUrl: '', /* callMyFunction('/url'); */ })
.when('/url2', { templateUrl: '', /* callMyFunction('/url'); */ }) ....
这只是一个例子,我知道这行不通。但是让你知道我想做什么。如您所见,这会弄乱我的代码(您需要更多才能使它正常工作,因此您将为每个 .when()
获得大量额外代码,并且此代码在每个语句中完全一样(参数除外)。
所以我正在寻找一些可以在 .when()
之前或之后调用的函数(只要它被调用就没有意义)。
我在 Stack Overflow 上阅读了很多问题,但没有找到正确的答案。大多数问题的回答都是将其放入 Controller 中。然而,我必须调用的这个函数对于每条路线都是完全相同的。因此,我不想将它放在我所有的 Controller 中,而只是放在 routes.js 中,并在每个 when()
之后调用。
最佳答案
您正在寻找类似 $routeChangeSuccess
或 $routeChangeStart
的内容(参见 $route
)。
路线变更前
function runConfig($rootScope) {
$rootScope.$on('$routeChangeStart', function (event, next, current) {
if (next && next['$$route']) {
var route = next['$$route']['originalPath'];
//route is 'url', 'url1' or 'urlX'
//do with it as you please
}
});
}
angular
.module('app')
.run(runConfig);
路线改变后
function runConfig($rootScope) {
$rootScope.$on('$routeChangeSuccess', function (event, current, prev) {
if (current && current['$$route']) {
var route = current['$$route']['originalPath'];
//route is 'url', 'url1' or 'urlX'
//do with it as you please
}
});
}
angular
.module('app')
.run(runConfig);
关于angularjs - $routeProvider 中每条路由的调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44951008/