我遇到了您描述的完全相同的问题。我的应用程序中到处都是硬编码的网址,更改任何内容都是一场噩梦。所以我决定想出一个好的解决方案。这就是我最终决定的。它可能并不完美,但到目前为止我还没有遇到任何问题。PS。我的应用程序很大,所以有很多网址需要跟踪。
.constant('RoutePaths', {
login: {
login: '/login',
eula: '/login/eula',
noSubscription: '/no-subscription',
myAccount: '/my-account',
createAccount: '/my-account/create',
createAccountFromXID: '/my-account/update',
...
// more routes here
},
conreg: {
compInfo: '/bronze/companyInfo',
serviceArea: '/bronze/serviceArea',
licenses: '/bronze/licenses',
insuranceBonds: '/bronze/insuranceAndBonds',
certifiedReviews: '/silver/certifiedReviews',
certifications: '/silver/certifications',
yearsAndBBB: '/silver/yearsAndBBB',
...
// more routes here
},
....
// more objects here
}
因为我已将此RoutePaths
对象声明为constant
,所以我现在可以在我的应用程序config
模块中将其与内置对象一起使用$routeProvider
:
app.config(['$routeProvider','RoutePaths', function($routeProvider, RoutePaths){
var login = RoutePaths.login;
$routeProvider
.when(login.login, {templateUrl: '../partials/login/login.html', controller: 'LoginCtrl'})
.when(login.eula, {templateUrl: '../partials/login/eula.html', controller: 'EulaCtrl'})
.when(login.myAccount, {templateUrl: '../partials/login/account.html', controller: 'AccountCtrl'})
...
// more routes declared here
}]);
您可以将相同的RoutePaths
依赖项注入您需要的任何控制器、服务、工厂、过滤器等:
.controller('LoginCtrl', ['$scope','RoutePaths', function($scope, RoutePaths){
$scope.paths = RoutePaths.login;
...
}]);
在您的视图中,您可以使用以下方式绑定到这些路径:
<a ng-href="{{paths.myAccount}}">My Account</a>
然后我必须进行任何更改,我可以在RoutePaths
常量内进行更改,并且它们会在我的应用程序中随处更新。它非常适合我的目的。您是在寻找更强大的东西还是对您有用?