Project

General

Profile

1
/**
2
 * @license AngularJS v1.4.1
3
 * (c) 2010-2015 Google, Inc. http://angularjs.org
4
 * License: MIT
5
 */
6
(function(window, angular, undefined) {'use strict';
7

    
8
/**
9
 * @ngdoc module
10
 * @name ngRoute
11
 * @description
12
 *
13
 * # ngRoute
14
 *
15
 * The `ngRoute` module provides routing and deeplinking services and directives for angular apps.
16
 *
17
 * ## Example
18
 * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
19
 *
20
 *
21
 * <div doc-module-components="ngRoute"></div>
22
 */
23
 /* global -ngRouteModule */
24
var ngRouteModule = angular.module('ngRoute', ['ng']).
25
                        provider('$route', $RouteProvider),
26
    $routeMinErr = angular.$$minErr('ngRoute');
27

    
28
/**
29
 * @ngdoc provider
30
 * @name $routeProvider
31
 *
32
 * @description
33
 *
34
 * Used for configuring routes.
35
 *
36
 * ## Example
37
 * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`.
38
 *
39
 * ## Dependencies
40
 * Requires the {@link ngRoute `ngRoute`} module to be installed.
41
 */
42
function $RouteProvider() {
43
  function inherit(parent, extra) {
44
    return angular.extend(Object.create(parent), extra);
45
  }
46

    
47
  var routes = {};
48

    
49
  /**
50
   * @ngdoc method
51
   * @name $routeProvider#when
52
   *
53
   * @param {string} path Route path (matched against `$location.path`). If `$location.path`
54
   *    contains redundant trailing slash or is missing one, the route will still match and the
55
   *    `$location.path` will be updated to add or drop the trailing slash to exactly match the
56
   *    route definition.
57
   *
58
   *    * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up
59
   *        to the next slash are matched and stored in `$routeParams` under the given `name`
60
   *        when the route matches.
61
   *    * `path` can contain named groups starting with a colon and ending with a star:
62
   *        e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name`
63
   *        when the route matches.
64
   *    * `path` can contain optional named groups with a question mark: e.g.`:name?`.
65
   *
66
   *    For example, routes like `/color/:color/largecode/:largecode*\/edit` will match
67
   *    `/color/brown/largecode/code/with/slashes/edit` and extract:
68
   *
69
   *    * `color: brown`
70
   *    * `largecode: code/with/slashes`.
71
   *
72
   *
73
   * @param {Object} route Mapping information to be assigned to `$route.current` on route
74
   *    match.
75
   *
76
   *    Object properties:
77
   *
78
   *    - `controller` – `{(string|function()=}` – Controller fn that should be associated with
79
   *      newly created scope or the name of a {@link angular.Module#controller registered
80
   *      controller} if passed as a string.
81
   *    - `controllerAs` – `{string=}` – An identifier name for a reference to the controller.
82
   *      If present, the controller will be published to scope under the `controllerAs` name.
83
   *    - `template` – `{string=|function()=}` – html template as a string or a function that
84
   *      returns an html template as a string which should be used by {@link
85
   *      ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives.
86
   *      This property takes precedence over `templateUrl`.
87
   *
88
   *      If `template` is a function, it will be called with the following parameters:
89
   *
90
   *      - `{Array.<Object>}` - route parameters extracted from the current
91
   *        `$location.path()` by applying the current route
92
   *
93
   *    - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html
94
   *      template that should be used by {@link ngRoute.directive:ngView ngView}.
95
   *
96
   *      If `templateUrl` is a function, it will be called with the following parameters:
97
   *
98
   *      - `{Array.<Object>}` - route parameters extracted from the current
99
   *        `$location.path()` by applying the current route
100
   *
101
   *    - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
102
   *      be injected into the controller. If any of these dependencies are promises, the router
103
   *      will wait for them all to be resolved or one to be rejected before the controller is
104
   *      instantiated.
105
   *      If all the promises are resolved successfully, the values of the resolved promises are
106
   *      injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is
107
   *      fired. If any of the promises are rejected the
108
   *      {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object
109
   *      is:
110
   *
111
   *      - `key` – `{string}`: a name of a dependency to be injected into the controller.
112
   *      - `factory` - `{string|function}`: If `string` then it is an alias for a service.
113
   *        Otherwise if function, then it is {@link auto.$injector#invoke injected}
114
   *        and the return value is treated as the dependency. If the result is a promise, it is
115
   *        resolved before its value is injected into the controller. Be aware that
116
   *        `ngRoute.$routeParams` will still refer to the previous route within these resolve
117
   *        functions.  Use `$route.current.params` to access the new route parameters, instead.
118
   *
119
   *    - `redirectTo` – {(string|function())=} – value to update
120
   *      {@link ng.$location $location} path with and trigger route redirection.
121
   *
122
   *      If `redirectTo` is a function, it will be called with the following parameters:
123
   *
124
   *      - `{Object.<string>}` - route parameters extracted from the current
125
   *        `$location.path()` by applying the current route templateUrl.
126
   *      - `{string}` - current `$location.path()`
127
   *      - `{Object}` - current `$location.search()`
128
   *
129
   *      The custom `redirectTo` function is expected to return a string which will be used
130
   *      to update `$location.path()` and `$location.search()`.
131
   *
132
   *    - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()`
133
   *      or `$location.hash()` changes.
134
   *
135
   *      If the option is set to `false` and url in the browser changes, then
136
   *      `$routeUpdate` event is broadcasted on the root scope.
137
   *
138
   *    - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive
139
   *
140
   *      If the option is set to `true`, then the particular route can be matched without being
141
   *      case sensitive
142
   *
143
   * @returns {Object} self
144
   *
145
   * @description
146
   * Adds a new route definition to the `$route` service.
147
   */
148
  this.when = function(path, route) {
149
    //copy original route object to preserve params inherited from proto chain
150
    var routeCopy = angular.copy(route);
151
    if (angular.isUndefined(routeCopy.reloadOnSearch)) {
152
      routeCopy.reloadOnSearch = true;
153
    }
154
    if (angular.isUndefined(routeCopy.caseInsensitiveMatch)) {
155
      routeCopy.caseInsensitiveMatch = this.caseInsensitiveMatch;
156
    }
157
    routes[path] = angular.extend(
158
      routeCopy,
159
      path && pathRegExp(path, routeCopy)
160
    );
161

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

    
168
      routes[redirectPath] = angular.extend(
169
        {redirectTo: path},
170
        pathRegExp(redirectPath, routeCopy)
171
      );
172
    }
173

    
174
    return this;
175
  };
176

    
177
  /**
178
   * @ngdoc property
179
   * @name $routeProvider#caseInsensitiveMatch
180
   * @description
181
   *
182
   * A boolean property indicating if routes defined
183
   * using this provider should be matched using a case insensitive
184
   * algorithm. Defaults to `false`.
185
   */
186
  this.caseInsensitiveMatch = false;
187

    
188
   /**
189
    * @param path {string} path
190
    * @param opts {Object} options
191
    * @return {?Object}
192
    *
193
    * @description
194
    * Normalizes the given path, returning a regular expression
195
    * and the original path.
196
    *
197
    * Inspired by pathRexp in visionmedia/express/lib/utils.js.
198
    */
199
  function pathRegExp(path, opts) {
200
    var insensitive = opts.caseInsensitiveMatch,
201
        ret = {
202
          originalPath: path,
203
          regexp: path
204
        },
205
        keys = ret.keys = [];
206

    
207
    path = path
208
      .replace(/([().])/g, '\\$1')
209
      .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option) {
210
        var optional = option === '?' ? option : null;
211
        var star = option === '*' ? option : null;
212
        keys.push({ name: key, optional: !!optional });
213
        slash = slash || '';
214
        return ''
215
          + (optional ? '' : slash)
216
          + '(?:'
217
          + (optional ? slash : '')
218
          + (star && '(.+?)' || '([^/]+)')
219
          + (optional || '')
220
          + ')'
221
          + (optional || '');
222
      })
223
      .replace(/([\/$\*])/g, '\\$1');
224

    
225
    ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
226
    return ret;
227
  }
228

    
229
  /**
230
   * @ngdoc method
231
   * @name $routeProvider#otherwise
232
   *
233
   * @description
234
   * Sets route definition that will be used on route change when no other route definition
235
   * is matched.
236
   *
237
   * @param {Object|string} params Mapping information to be assigned to `$route.current`.
238
   * If called with a string, the value maps to `redirectTo`.
239
   * @returns {Object} self
240
   */
241
  this.otherwise = function(params) {
242
    if (typeof params === 'string') {
243
      params = {redirectTo: params};
244
    }
245
    this.when(null, params);
246
    return this;
247
  };
248

    
249

    
250
  this.$get = ['$rootScope',
251
               '$location',
252
               '$routeParams',
253
               '$q',
254
               '$injector',
255
               '$templateRequest',
256
               '$sce',
257
      function($rootScope, $location, $routeParams, $q, $injector, $templateRequest, $sce) {
258

    
259
    /**
260
     * @ngdoc service
261
     * @name $route
262
     * @requires $location
263
     * @requires $routeParams
264
     *
265
     * @property {Object} current Reference to the current route definition.
266
     * The route definition contains:
267
     *
268
     *   - `controller`: The controller constructor as define in route definition.
269
     *   - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
270
     *     controller instantiation. The `locals` contain
271
     *     the resolved values of the `resolve` map. Additionally the `locals` also contain:
272
     *
273
     *     - `$scope` - The current route scope.
274
     *     - `$template` - The current route template HTML.
275
     *
276
     * @property {Object} routes Object with all route configuration Objects as its properties.
277
     *
278
     * @description
279
     * `$route` is used for deep-linking URLs to controllers and views (HTML partials).
280
     * It watches `$location.url()` and tries to map the path to an existing route definition.
281
     *
282
     * Requires the {@link ngRoute `ngRoute`} module to be installed.
283
     *
284
     * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
285
     *
286
     * The `$route` service is typically used in conjunction with the
287
     * {@link ngRoute.directive:ngView `ngView`} directive and the
288
     * {@link ngRoute.$routeParams `$routeParams`} service.
289
     *
290
     * @example
291
     * This example shows how changing the URL hash causes the `$route` to match a route against the
292
     * URL, and the `ngView` pulls in the partial.
293
     *
294
     * <example name="$route-service" module="ngRouteExample"
295
     *          deps="angular-route.js" fixBase="true">
296
     *   <file name="index.html">
297
     *     <div ng-controller="MainController">
298
     *       Choose:
299
     *       <a href="Book/Moby">Moby</a> |
300
     *       <a href="Book/Moby/ch/1">Moby: Ch1</a> |
301
     *       <a href="Book/Gatsby">Gatsby</a> |
302
     *       <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
303
     *       <a href="Book/Scarlet">Scarlet Letter</a><br/>
304
     *
305
     *       <div ng-view></div>
306
     *
307
     *       <hr />
308
     *
309
     *       <pre>$location.path() = {{$location.path()}}</pre>
310
     *       <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
311
     *       <pre>$route.current.params = {{$route.current.params}}</pre>
312
     *       <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
313
     *       <pre>$routeParams = {{$routeParams}}</pre>
314
     *     </div>
315
     *   </file>
316
     *
317
     *   <file name="book.html">
318
     *     controller: {{name}}<br />
319
     *     Book Id: {{params.bookId}}<br />
320
     *   </file>
321
     *
322
     *   <file name="chapter.html">
323
     *     controller: {{name}}<br />
324
     *     Book Id: {{params.bookId}}<br />
325
     *     Chapter Id: {{params.chapterId}}
326
     *   </file>
327
     *
328
     *   <file name="script.js">
329
     *     angular.module('ngRouteExample', ['ngRoute'])
330
     *
331
     *      .controller('MainController', function($scope, $route, $routeParams, $location) {
332
     *          $scope.$route = $route;
333
     *          $scope.$location = $location;
334
     *          $scope.$routeParams = $routeParams;
335
     *      })
336
     *
337
     *      .controller('BookController', function($scope, $routeParams) {
338
     *          $scope.name = "BookController";
339
     *          $scope.params = $routeParams;
340
     *      })
341
     *
342
     *      .controller('ChapterController', function($scope, $routeParams) {
343
     *          $scope.name = "ChapterController";
344
     *          $scope.params = $routeParams;
345
     *      })
346
     *
347
     *     .config(function($routeProvider, $locationProvider) {
348
     *       $routeProvider
349
     *        .when('/Book/:bookId', {
350
     *         templateUrl: 'book.html',
351
     *         controller: 'BookController',
352
     *         resolve: {
353
     *           // I will cause a 1 second delay
354
     *           delay: function($q, $timeout) {
355
     *             var delay = $q.defer();
356
     *             $timeout(delay.resolve, 1000);
357
     *             return delay.promise;
358
     *           }
359
     *         }
360
     *       })
361
     *       .when('/Book/:bookId/ch/:chapterId', {
362
     *         templateUrl: 'chapter.html',
363
     *         controller: 'ChapterController'
364
     *       });
365
     *
366
     *       // configure html5 to get links working on jsfiddle
367
     *       $locationProvider.html5Mode(true);
368
     *     });
369
     *
370
     *   </file>
371
     *
372
     *   <file name="protractor.js" type="protractor">
373
     *     it('should load and compile correct template', function() {
374
     *       element(by.linkText('Moby: Ch1')).click();
375
     *       var content = element(by.css('[ng-view]')).getText();
376
     *       expect(content).toMatch(/controller\: ChapterController/);
377
     *       expect(content).toMatch(/Book Id\: Moby/);
378
     *       expect(content).toMatch(/Chapter Id\: 1/);
379
     *
380
     *       element(by.partialLinkText('Scarlet')).click();
381
     *
382
     *       content = element(by.css('[ng-view]')).getText();
383
     *       expect(content).toMatch(/controller\: BookController/);
384
     *       expect(content).toMatch(/Book Id\: Scarlet/);
385
     *     });
386
     *   </file>
387
     * </example>
388
     */
389

    
390
    /**
391
     * @ngdoc event
392
     * @name $route#$routeChangeStart
393
     * @eventType broadcast on root scope
394
     * @description
395
     * Broadcasted before a route change. At this  point the route services starts
396
     * resolving all of the dependencies needed for the route change to occur.
397
     * Typically this involves fetching the view template as well as any dependencies
398
     * defined in `resolve` route property. Once  all of the dependencies are resolved
399
     * `$routeChangeSuccess` is fired.
400
     *
401
     * The route change (and the `$location` change that triggered it) can be prevented
402
     * by calling `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on}
403
     * for more details about event object.
404
     *
405
     * @param {Object} angularEvent Synthetic event object.
406
     * @param {Route} next Future route information.
407
     * @param {Route} current Current route information.
408
     */
409

    
410
    /**
411
     * @ngdoc event
412
     * @name $route#$routeChangeSuccess
413
     * @eventType broadcast on root scope
414
     * @description
415
     * Broadcasted after a route dependencies are resolved.
416
     * {@link ngRoute.directive:ngView ngView} listens for the directive
417
     * to instantiate the controller and render the view.
418
     *
419
     * @param {Object} angularEvent Synthetic event object.
420
     * @param {Route} current Current route information.
421
     * @param {Route|Undefined} previous Previous route information, or undefined if current is
422
     * first route entered.
423
     */
424

    
425
    /**
426
     * @ngdoc event
427
     * @name $route#$routeChangeError
428
     * @eventType broadcast on root scope
429
     * @description
430
     * Broadcasted if any of the resolve promises are rejected.
431
     *
432
     * @param {Object} angularEvent Synthetic event object
433
     * @param {Route} current Current route information.
434
     * @param {Route} previous Previous route information.
435
     * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
436
     */
437

    
438
    /**
439
     * @ngdoc event
440
     * @name $route#$routeUpdate
441
     * @eventType broadcast on root scope
442
     * @description
443
     * The `reloadOnSearch` property has been set to false, and we are reusing the same
444
     * instance of the Controller.
445
     *
446
     * @param {Object} angularEvent Synthetic event object
447
     * @param {Route} current Current/previous route information.
448
     */
449

    
450
    var forceReload = false,
451
        preparedRoute,
452
        preparedRouteIsUpdateOnly,
453
        $route = {
454
          routes: routes,
455

    
456
          /**
457
           * @ngdoc method
458
           * @name $route#reload
459
           *
460
           * @description
461
           * Causes `$route` service to reload the current route even if
462
           * {@link ng.$location $location} hasn't changed.
463
           *
464
           * As a result of that, {@link ngRoute.directive:ngView ngView}
465
           * creates new scope and reinstantiates the controller.
466
           */
467
          reload: function() {
468
            forceReload = true;
469
            $rootScope.$evalAsync(function() {
470
              // Don't support cancellation of a reload for now...
471
              prepareRoute();
472
              commitRoute();
473
            });
474
          },
475

    
476
          /**
477
           * @ngdoc method
478
           * @name $route#updateParams
479
           *
480
           * @description
481
           * Causes `$route` service to update the current URL, replacing
482
           * current route parameters with those specified in `newParams`.
483
           * Provided property names that match the route's path segment
484
           * definitions will be interpolated into the location's path, while
485
           * remaining properties will be treated as query params.
486
           *
487
           * @param {!Object<string, string>} newParams mapping of URL parameter names to values
488
           */
489
          updateParams: function(newParams) {
490
            if (this.current && this.current.$$route) {
491
              newParams = angular.extend({}, this.current.params, newParams);
492
              $location.path(interpolate(this.current.$$route.originalPath, newParams));
493
              // interpolate modifies newParams, only query params are left
494
              $location.search(newParams);
495
            } else {
496
              throw $routeMinErr('norout', 'Tried updating route when with no current route');
497
            }
498
          }
499
        };
500

    
501
    $rootScope.$on('$locationChangeStart', prepareRoute);
502
    $rootScope.$on('$locationChangeSuccess', commitRoute);
503

    
504
    return $route;
505

    
506
    /////////////////////////////////////////////////////
507

    
508
    /**
509
     * @param on {string} current url
510
     * @param route {Object} route regexp to match the url against
511
     * @return {?Object}
512
     *
513
     * @description
514
     * Check if the route matches the current url.
515
     *
516
     * Inspired by match in
517
     * visionmedia/express/lib/router/router.js.
518
     */
519
    function switchRouteMatcher(on, route) {
520
      var keys = route.keys,
521
          params = {};
522

    
523
      if (!route.regexp) return null;
524

    
525
      var m = route.regexp.exec(on);
526
      if (!m) return null;
527

    
528
      for (var i = 1, len = m.length; i < len; ++i) {
529
        var key = keys[i - 1];
530

    
531
        var val = m[i];
532

    
533
        if (key && val) {
534
          params[key.name] = val;
535
        }
536
      }
537
      return params;
538
    }
539

    
540
    function prepareRoute($locationEvent) {
541
      var lastRoute = $route.current;
542

    
543
      preparedRoute = parseRoute();
544
      preparedRouteIsUpdateOnly = preparedRoute && lastRoute && preparedRoute.$$route === lastRoute.$$route
545
          && angular.equals(preparedRoute.pathParams, lastRoute.pathParams)
546
          && !preparedRoute.reloadOnSearch && !forceReload;
547

    
548
      if (!preparedRouteIsUpdateOnly && (lastRoute || preparedRoute)) {
549
        if ($rootScope.$broadcast('$routeChangeStart', preparedRoute, lastRoute).defaultPrevented) {
550
          if ($locationEvent) {
551
            $locationEvent.preventDefault();
552
          }
553
        }
554
      }
555
    }
556

    
557
    function commitRoute() {
558
      var lastRoute = $route.current;
559
      var nextRoute = preparedRoute;
560

    
561
      if (preparedRouteIsUpdateOnly) {
562
        lastRoute.params = nextRoute.params;
563
        angular.copy(lastRoute.params, $routeParams);
564
        $rootScope.$broadcast('$routeUpdate', lastRoute);
565
      } else if (nextRoute || lastRoute) {
566
        forceReload = false;
567
        $route.current = nextRoute;
568
        if (nextRoute) {
569
          if (nextRoute.redirectTo) {
570
            if (angular.isString(nextRoute.redirectTo)) {
571
              $location.path(interpolate(nextRoute.redirectTo, nextRoute.params)).search(nextRoute.params)
572
                       .replace();
573
            } else {
574
              $location.url(nextRoute.redirectTo(nextRoute.pathParams, $location.path(), $location.search()))
575
                       .replace();
576
            }
577
          }
578
        }
579

    
580
        $q.when(nextRoute).
581
          then(function() {
582
            if (nextRoute) {
583
              var locals = angular.extend({}, nextRoute.resolve),
584
                  template, templateUrl;
585

    
586
              angular.forEach(locals, function(value, key) {
587
                locals[key] = angular.isString(value) ?
588
                    $injector.get(value) : $injector.invoke(value, null, null, key);
589
              });
590

    
591
              if (angular.isDefined(template = nextRoute.template)) {
592
                if (angular.isFunction(template)) {
593
                  template = template(nextRoute.params);
594
                }
595
              } else if (angular.isDefined(templateUrl = nextRoute.templateUrl)) {
596
                if (angular.isFunction(templateUrl)) {
597
                  templateUrl = templateUrl(nextRoute.params);
598
                }
599
                templateUrl = $sce.getTrustedResourceUrl(templateUrl);
600
                if (angular.isDefined(templateUrl)) {
601
                  nextRoute.loadedTemplateUrl = templateUrl;
602
                  template = $templateRequest(templateUrl);
603
                }
604
              }
605
              if (angular.isDefined(template)) {
606
                locals['$template'] = template;
607
              }
608
              return $q.all(locals);
609
            }
610
          }).
611
          then(function(locals) {
612
            // after route change
613
            if (nextRoute == $route.current) {
614
              if (nextRoute) {
615
                nextRoute.locals = locals;
616
                angular.copy(nextRoute.params, $routeParams);
617
              }
618
              $rootScope.$broadcast('$routeChangeSuccess', nextRoute, lastRoute);
619
            }
620
          }, function(error) {
621
            if (nextRoute == $route.current) {
622
              $rootScope.$broadcast('$routeChangeError', nextRoute, lastRoute, error);
623
            }
624
          });
625
      }
626
    }
627

    
628

    
629
    /**
630
     * @returns {Object} the current active route, by matching it against the URL
631
     */
632
    function parseRoute() {
633
      // Match a route
634
      var params, match;
635
      angular.forEach(routes, function(route, path) {
636
        if (!match && (params = switchRouteMatcher($location.path(), route))) {
637
          match = inherit(route, {
638
            params: angular.extend({}, $location.search(), params),
639
            pathParams: params});
640
          match.$$route = route;
641
        }
642
      });
643
      // No route matched; fallback to "otherwise" route
644
      return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
645
    }
646

    
647
    /**
648
     * @returns {string} interpolation of the redirect path with the parameters
649
     */
650
    function interpolate(string, params) {
651
      var result = [];
652
      angular.forEach((string || '').split(':'), function(segment, i) {
653
        if (i === 0) {
654
          result.push(segment);
655
        } else {
656
          var segmentMatch = segment.match(/(\w+)(?:[?*])?(.*)/);
657
          var key = segmentMatch[1];
658
          result.push(params[key]);
659
          result.push(segmentMatch[2] || '');
660
          delete params[key];
661
        }
662
      });
663
      return result.join('');
664
    }
665
  }];
666
}
667

    
668
ngRouteModule.provider('$routeParams', $RouteParamsProvider);
669

    
670

    
671
/**
672
 * @ngdoc service
673
 * @name $routeParams
674
 * @requires $route
675
 *
676
 * @description
677
 * The `$routeParams` service allows you to retrieve the current set of route parameters.
678
 *
679
 * Requires the {@link ngRoute `ngRoute`} module to be installed.
680
 *
681
 * The route parameters are a combination of {@link ng.$location `$location`}'s
682
 * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
683
 * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
684
 *
685
 * In case of parameter name collision, `path` params take precedence over `search` params.
686
 *
687
 * The service guarantees that the identity of the `$routeParams` object will remain unchanged
688
 * (but its properties will likely change) even when a route change occurs.
689
 *
690
 * Note that the `$routeParams` are only updated *after* a route change completes successfully.
691
 * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
692
 * Instead you can use `$route.current.params` to access the new route's parameters.
693
 *
694
 * @example
695
 * ```js
696
 *  // Given:
697
 *  // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
698
 *  // Route: /Chapter/:chapterId/Section/:sectionId
699
 *  //
700
 *  // Then
701
 *  $routeParams ==> {chapterId:'1', sectionId:'2', search:'moby'}
702
 * ```
703
 */
704
function $RouteParamsProvider() {
705
  this.$get = function() { return {}; };
706
}
707

    
708
ngRouteModule.directive('ngView', ngViewFactory);
709
ngRouteModule.directive('ngView', ngViewFillContentFactory);
710

    
711

    
712
/**
713
 * @ngdoc directive
714
 * @name ngView
715
 * @restrict ECA
716
 *
717
 * @description
718
 * # Overview
719
 * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
720
 * including the rendered template of the current route into the main layout (`index.html`) file.
721
 * Every time the current route changes, the included view changes with it according to the
722
 * configuration of the `$route` service.
723
 *
724
 * Requires the {@link ngRoute `ngRoute`} module to be installed.
725
 *
726
 * @animations
727
 * enter - animation is used to bring new content into the browser.
728
 * leave - animation is used to animate existing content away.
729
 *
730
 * The enter and leave animation occur concurrently.
731
 *
732
 * @scope
733
 * @priority 400
734
 * @param {string=} onload Expression to evaluate whenever the view updates.
735
 *
736
 * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
737
 *                  $anchorScroll} to scroll the viewport after the view is updated.
738
 *
739
 *                  - If the attribute is not set, disable scrolling.
740
 *                  - If the attribute is set without value, enable scrolling.
741
 *                  - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
742
 *                    as an expression yields a truthy value.
743
 * @example
744
    <example name="ngView-directive" module="ngViewExample"
745
             deps="angular-route.js;angular-animate.js"
746
             animations="true" fixBase="true">
747
      <file name="index.html">
748
        <div ng-controller="MainCtrl as main">
749
          Choose:
750
          <a href="Book/Moby">Moby</a> |
751
          <a href="Book/Moby/ch/1">Moby: Ch1</a> |
752
          <a href="Book/Gatsby">Gatsby</a> |
753
          <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
754
          <a href="Book/Scarlet">Scarlet Letter</a><br/>
755

    
756
          <div class="view-animate-container">
757
            <div ng-view class="view-animate"></div>
758
          </div>
759
          <hr />
760

    
761
          <pre>$location.path() = {{main.$location.path()}}</pre>
762
          <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
763
          <pre>$route.current.params = {{main.$route.current.params}}</pre>
764
          <pre>$routeParams = {{main.$routeParams}}</pre>
765
        </div>
766
      </file>
767

    
768
      <file name="book.html">
769
        <div>
770
          controller: {{book.name}}<br />
771
          Book Id: {{book.params.bookId}}<br />
772
        </div>
773
      </file>
774

    
775
      <file name="chapter.html">
776
        <div>
777
          controller: {{chapter.name}}<br />
778
          Book Id: {{chapter.params.bookId}}<br />
779
          Chapter Id: {{chapter.params.chapterId}}
780
        </div>
781
      </file>
782

    
783
      <file name="animations.css">
784
        .view-animate-container {
785
          position:relative;
786
          height:100px!important;
787
          background:white;
788
          border:1px solid black;
789
          height:40px;
790
          overflow:hidden;
791
        }
792

    
793
        .view-animate {
794
          padding:10px;
795
        }
796

    
797
        .view-animate.ng-enter, .view-animate.ng-leave {
798
          -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
799
          transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
800

    
801
          display:block;
802
          width:100%;
803
          border-left:1px solid black;
804

    
805
          position:absolute;
806
          top:0;
807
          left:0;
808
          right:0;
809
          bottom:0;
810
          padding:10px;
811
        }
812

    
813
        .view-animate.ng-enter {
814
          left:100%;
815
        }
816
        .view-animate.ng-enter.ng-enter-active {
817
          left:0;
818
        }
819
        .view-animate.ng-leave.ng-leave-active {
820
          left:-100%;
821
        }
822
      </file>
823

    
824
      <file name="script.js">
825
        angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
826
          .config(['$routeProvider', '$locationProvider',
827
            function($routeProvider, $locationProvider) {
828
              $routeProvider
829
                .when('/Book/:bookId', {
830
                  templateUrl: 'book.html',
831
                  controller: 'BookCtrl',
832
                  controllerAs: 'book'
833
                })
834
                .when('/Book/:bookId/ch/:chapterId', {
835
                  templateUrl: 'chapter.html',
836
                  controller: 'ChapterCtrl',
837
                  controllerAs: 'chapter'
838
                });
839

    
840
              $locationProvider.html5Mode(true);
841
          }])
842
          .controller('MainCtrl', ['$route', '$routeParams', '$location',
843
            function($route, $routeParams, $location) {
844
              this.$route = $route;
845
              this.$location = $location;
846
              this.$routeParams = $routeParams;
847
          }])
848
          .controller('BookCtrl', ['$routeParams', function($routeParams) {
849
            this.name = "BookCtrl";
850
            this.params = $routeParams;
851
          }])
852
          .controller('ChapterCtrl', ['$routeParams', function($routeParams) {
853
            this.name = "ChapterCtrl";
854
            this.params = $routeParams;
855
          }]);
856

    
857
      </file>
858

    
859
      <file name="protractor.js" type="protractor">
860
        it('should load and compile correct template', function() {
861
          element(by.linkText('Moby: Ch1')).click();
862
          var content = element(by.css('[ng-view]')).getText();
863
          expect(content).toMatch(/controller\: ChapterCtrl/);
864
          expect(content).toMatch(/Book Id\: Moby/);
865
          expect(content).toMatch(/Chapter Id\: 1/);
866

    
867
          element(by.partialLinkText('Scarlet')).click();
868

    
869
          content = element(by.css('[ng-view]')).getText();
870
          expect(content).toMatch(/controller\: BookCtrl/);
871
          expect(content).toMatch(/Book Id\: Scarlet/);
872
        });
873
      </file>
874
    </example>
875
 */
876

    
877

    
878
/**
879
 * @ngdoc event
880
 * @name ngView#$viewContentLoaded
881
 * @eventType emit on the current ngView scope
882
 * @description
883
 * Emitted every time the ngView content is reloaded.
884
 */
885
ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
886
function ngViewFactory($route, $anchorScroll, $animate) {
887
  return {
888
    restrict: 'ECA',
889
    terminal: true,
890
    priority: 400,
891
    transclude: 'element',
892
    link: function(scope, $element, attr, ctrl, $transclude) {
893
        var currentScope,
894
            currentElement,
895
            previousLeaveAnimation,
896
            autoScrollExp = attr.autoscroll,
897
            onloadExp = attr.onload || '';
898

    
899
        scope.$on('$routeChangeSuccess', update);
900
        update();
901

    
902
        function cleanupLastView() {
903
          if (previousLeaveAnimation) {
904
            $animate.cancel(previousLeaveAnimation);
905
            previousLeaveAnimation = null;
906
          }
907

    
908
          if (currentScope) {
909
            currentScope.$destroy();
910
            currentScope = null;
911
          }
912
          if (currentElement) {
913
            previousLeaveAnimation = $animate.leave(currentElement);
914
            previousLeaveAnimation.then(function() {
915
              previousLeaveAnimation = null;
916
            });
917
            currentElement = null;
918
          }
919
        }
920

    
921
        function update() {
922
          var locals = $route.current && $route.current.locals,
923
              template = locals && locals.$template;
924

    
925
          if (angular.isDefined(template)) {
926
            var newScope = scope.$new();
927
            var current = $route.current;
928

    
929
            // Note: This will also link all children of ng-view that were contained in the original
930
            // html. If that content contains controllers, ... they could pollute/change the scope.
931
            // However, using ng-view on an element with additional content does not make sense...
932
            // Note: We can't remove them in the cloneAttchFn of $transclude as that
933
            // function is called before linking the content, which would apply child
934
            // directives to non existing elements.
935
            var clone = $transclude(newScope, function(clone) {
936
              $animate.enter(clone, null, currentElement || $element).then(function onNgViewEnter() {
937
                if (angular.isDefined(autoScrollExp)
938
                  && (!autoScrollExp || scope.$eval(autoScrollExp))) {
939
                  $anchorScroll();
940
                }
941
              });
942
              cleanupLastView();
943
            });
944

    
945
            currentElement = clone;
946
            currentScope = current.scope = newScope;
947
            currentScope.$emit('$viewContentLoaded');
948
            currentScope.$eval(onloadExp);
949
          } else {
950
            cleanupLastView();
951
          }
952
        }
953
    }
954
  };
955
}
956

    
957
// This directive is called during the $transclude call of the first `ngView` directive.
958
// It will replace and compile the content of the element with the loaded template.
959
// We need this directive so that the element content is already filled when
960
// the link function of another directive on the same element as ngView
961
// is called.
962
ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
963
function ngViewFillContentFactory($compile, $controller, $route) {
964
  return {
965
    restrict: 'ECA',
966
    priority: -400,
967
    link: function(scope, $element) {
968
      var current = $route.current,
969
          locals = current.locals;
970

    
971
      $element.html(locals.$template);
972

    
973
      var link = $compile($element.contents());
974

    
975
      if (current.controller) {
976
        locals.$scope = scope;
977
        var controller = $controller(current.controller, locals);
978
        if (current.controllerAs) {
979
          scope[current.controllerAs] = controller;
980
        }
981
        $element.data('$ngControllerController', controller);
982
        $element.children().data('$ngControllerController', controller);
983
      }
984

    
985
      link(scope);
986
    }
987
  };
988
}
989

    
990

    
991
})(window, window.angular);
(3-3/8)