2

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!

2
  • Would this help you: stackoverflow.com/questions/13681116/… Commented Feb 10, 2014 at 4:57
  • Unfortunately not. The reason why is because the html and route may not share the same value. For instance, I could have an entry that looks like { name: 'other', route:'/somewhere/rainbow', html:'/root/site' } Commented Feb 10, 2014 at 11:40

1 Answer 1

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
                        });
                    });
Sign up to request clarification or add additional context in comments.

1 Comment

it's better if you add an explanation and provide more comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.