如何处理 AngularJS 应用程序中的路径管理



我有兴趣找出一种管理应用程序各个部分的路径(如URL中的)的智能方法。

如果你在 HTML(href属性)、控制器和服务($location.path()调用)中有它们,那么将 URL 从/login 更改为/auth 是非常混乱的。您必须遍历所有JS和HTML文件以查找对此的引用。

应该如何做到这一点?我将 path 对象视为一个angular.constant,它被注入到 HTML 文件范围内以供使用,并在控制器和服务中作为 JS 对象引用,以便有一个地方来保存它们。

这样做会是个好方法吗?有没有更好的方法?

谢谢。

我遇到了你描述的完全相同的问题。 我的应用程序中到处都是硬编码的网址,更改任何东西都是一场噩梦。 所以我决定想出一个好的解决方案。 这就是我最终决定的。 它可能并不完美,但到目前为止我还没有遇到任何问题。 我的应用程序很大,所以有很多网址需要跟踪。

.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常量内进行它们,并且它们在我的应用程序中的任何地方都会更新。 它非常适合我的目的。 您是在寻找更强大的产品还是适合您?

这可能会有所帮助,从 angular-ui/ui-router :

https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-sref

我现在几乎只使用 ui-router,所以我忘记了 angular 自己的路由器如何处理这个问题。

最新更新