简体   繁体   中英

Dynamically Add Routes in AngularJS

I have an AngularJS app built with version 1.2.5. I am trying to dynamically add routes. Currently, I have the following:

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' }
       ]});
    };
  })
;

While my sitemap is hard-coded, I would like to eventually pull this from a web service. That's why I want to rely on a function in a service. However, I can't figure out how to dynamically build the routes once I have them. Can someone please provide some insight?

Thank you!

// 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
                        });
                    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM