在AngularJS中动态添加路由

时间:2014-02-10 03:13:52

标签: javascript angularjs angular-routing

我有一个使用1.2.5版本构建的AngularJS应用程序。我正在尝试动态添加路线。目前,我有以下内容:

var sitemap = [];    
angular.module('app', ['ngRoute', 'ngAnimate'])
  .config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true);
    angular.forEach(sitemap, function (value, key) {
      $routeProvider.when(value.route, { templateUrl: value.html, controller: viewCtrl });
    });
    $routeProvider.otherwise({ templateUrl: '/views/default.html', controller: viewCtrl });
  })
  .service('navigationService', function () {
    this.loadItems = function () {
      console.log('loading items...');
      sitemap.push({
        name: 'dashboards', children: [
          { name: 'dashboard 1', route: '/dashboards/dashboard1', html: '' }
        ]
      });

      sitemap.push({
        name: 'views', children: [
          { name: 'historical', route: '/views/historical', html: '/views/historical.html' },
          { name: 'present', route: '/views/present', html: '/views/present.html' },
          { name: 'future', route: '/views/future', html: '/views/future.html' }
       ]});
    };
  })
;

虽然我的站点地图是硬编码的,但我想最终从网络服务中获取此信息。这就是我想要依赖服务中的功能的原因。但是,一旦我拥有它们,我无法弄清楚如何动态构建路由。有人可以提供一些见解吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

// version 1.0.1, after angular-route.js becomes an independent file in the later version, directly set the $route doesn't work.
                var pathRegExp = function (path, opts) {
                    var insensitive = opts.caseInsensitiveMatch,
                        ret = {
                            originalPath: path,
                            regexp: path
                        },
                        keys = ret.keys = [];

                    path = path.replace(/([().])/g, '\\$1')
                        .replace(/(\/)?:(\w+)([\?\*])?/g, function (_, slash, key, option) {
                            var optional = option === '?' ? option : null;
                            var star = option === '*' ? option : null;
                            keys.push({
                                name: key,
                                optional: !!optional
                            });
                            slash = slash || '';
                            return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || '');
                        })
                        .replace(/([\/$\*])/g, '\\$1');

                    ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
                    return ret;
                }
                var addRoute = function (path, route) {
                    $route.routes[path] = angular.extend(
                        {
                            reloadOnSearch: true
                        },
                        route,
                        path && pathRegExp(path, route));

                    // create redirection for trailing slashes
                    if (path) {
                        var redirectPath = (path[path.length - 1] == '/') ? path.substr(0, path.length - 1) : path + '/';

                        $route.routes[redirectPath] = angular.extend({
                            redirectTo: path
                        },
                        pathRegExp(redirectPath, route));
                    }

                    return this;
                };


angular.forEach(routing, function (item) {
                        addRoute(item.route, {
                            templateUrl: item.templateUrl,
                            controller: item.controller
                        });
                    });