4

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

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

这应该怎么做?我正在考虑一个路径对象,angular.constant它被注入到 HTML 文件的范围内,以便在控制器和服务中作为 JS 对象使用和引用,以便在一个地方保存它们。

这是一个很好的方法吗?有没有更好的办法?

谢谢。

4

2 回答 2

2

我遇到了您描述的完全相同的问题。我的应用程序中到处都是硬编码的网址,更改任何内容都是一场噩梦。所以我决定想出一个好的解决方案。这就是我最终决定的。它可能并不完美,但到目前为止我还没有遇到任何问题。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常量内进行更改,并且它们会在我的应用程序中随处更新。它非常适合我的目的。您是在寻找更强大的东西还是对您有用?

于 2013-11-13T14:53:54.857 回答
2

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

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

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

于 2013-11-13T13:45:57.873 回答