angularjs-rails 1.2.14 → 1.2.15

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,927 @@
1
+ /**
2
+ * @license AngularJS v1.3.0-beta.3
3
+ * (c) 2010-2014 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
+
27
+ /**
28
+ * @ngdoc provider
29
+ * @name $routeProvider
30
+ * @function
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(new (angular.extend(function() {}, {prototype: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=}` – A controller alias name. If present the controller will be
82
+ * 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
+ routes[path] = angular.extend(
150
+ {reloadOnSearch: true},
151
+ route,
152
+ path && pathRegExp(path, route)
153
+ );
154
+
155
+ // create redirection for trailing slashes
156
+ if (path) {
157
+ var redirectPath = (path[path.length-1] == '/')
158
+ ? path.substr(0, path.length-1)
159
+ : path +'/';
160
+
161
+ routes[redirectPath] = angular.extend(
162
+ {redirectTo: path},
163
+ pathRegExp(redirectPath, route)
164
+ );
165
+ }
166
+
167
+ return this;
168
+ };
169
+
170
+ /**
171
+ * @param path {string} path
172
+ * @param opts {Object} options
173
+ * @return {?Object}
174
+ *
175
+ * @description
176
+ * Normalizes the given path, returning a regular expression
177
+ * and the original path.
178
+ *
179
+ * Inspired by pathRexp in visionmedia/express/lib/utils.js.
180
+ */
181
+ function pathRegExp(path, opts) {
182
+ var insensitive = opts.caseInsensitiveMatch,
183
+ ret = {
184
+ originalPath: path,
185
+ regexp: path
186
+ },
187
+ keys = ret.keys = [];
188
+
189
+ path = path
190
+ .replace(/([().])/g, '\\$1')
191
+ .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){
192
+ var optional = option === '?' ? option : null;
193
+ var star = option === '*' ? option : null;
194
+ keys.push({ name: key, optional: !!optional });
195
+ slash = slash || '';
196
+ return ''
197
+ + (optional ? '' : slash)
198
+ + '(?:'
199
+ + (optional ? slash : '')
200
+ + (star && '(.+?)' || '([^/]+)')
201
+ + (optional || '')
202
+ + ')'
203
+ + (optional || '');
204
+ })
205
+ .replace(/([\/$\*])/g, '\\$1');
206
+
207
+ ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : '');
208
+ return ret;
209
+ }
210
+
211
+ /**
212
+ * @ngdoc method
213
+ * @name $routeProvider#otherwise
214
+ *
215
+ * @description
216
+ * Sets route definition that will be used on route change when no other route definition
217
+ * is matched.
218
+ *
219
+ * @param {Object} params Mapping information to be assigned to `$route.current`.
220
+ * @returns {Object} self
221
+ */
222
+ this.otherwise = function(params) {
223
+ this.when(null, params);
224
+ return this;
225
+ };
226
+
227
+
228
+ this.$get = ['$rootScope',
229
+ '$location',
230
+ '$routeParams',
231
+ '$q',
232
+ '$injector',
233
+ '$http',
234
+ '$templateCache',
235
+ '$sce',
236
+ function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) {
237
+
238
+ /**
239
+ * @ngdoc service
240
+ * @name $route
241
+ * @requires $location
242
+ * @requires $routeParams
243
+ *
244
+ * @property {Object} current Reference to the current route definition.
245
+ * The route definition contains:
246
+ *
247
+ * - `controller`: The controller constructor as define in route definition.
248
+ * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
249
+ * controller instantiation. The `locals` contain
250
+ * the resolved values of the `resolve` map. Additionally the `locals` also contain:
251
+ *
252
+ * - `$scope` - The current route scope.
253
+ * - `$template` - The current route template HTML.
254
+ *
255
+ * @property {Object} routes Object with all route configuration Objects as its properties.
256
+ *
257
+ * @description
258
+ * `$route` is used for deep-linking URLs to controllers and views (HTML partials).
259
+ * It watches `$location.url()` and tries to map the path to an existing route definition.
260
+ *
261
+ * Requires the {@link ngRoute `ngRoute`} module to be installed.
262
+ *
263
+ * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API.
264
+ *
265
+ * The `$route` service is typically used in conjunction with the
266
+ * {@link ngRoute.directive:ngView `ngView`} directive and the
267
+ * {@link ngRoute.$routeParams `$routeParams`} service.
268
+ *
269
+ * @example
270
+ * This example shows how changing the URL hash causes the `$route` to match a route against the
271
+ * URL, and the `ngView` pulls in the partial.
272
+ *
273
+ * Note that this example is using {@link ng.directive:script inlined templates}
274
+ * to get it working on jsfiddle as well.
275
+ *
276
+ * <example name="$route-service" module="ngRouteExample"
277
+ * deps="angular-route.js" fixBase="true">
278
+ * <file name="index.html">
279
+ * <div ng-controller="MainController">
280
+ * Choose:
281
+ * <a href="Book/Moby">Moby</a> |
282
+ * <a href="Book/Moby/ch/1">Moby: Ch1</a> |
283
+ * <a href="Book/Gatsby">Gatsby</a> |
284
+ * <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
285
+ * <a href="Book/Scarlet">Scarlet Letter</a><br/>
286
+ *
287
+ * <div ng-view></div>
288
+ *
289
+ * <hr />
290
+ *
291
+ * <pre>$location.path() = {{$location.path()}}</pre>
292
+ * <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
293
+ * <pre>$route.current.params = {{$route.current.params}}</pre>
294
+ * <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
295
+ * <pre>$routeParams = {{$routeParams}}</pre>
296
+ * </div>
297
+ * </file>
298
+ *
299
+ * <file name="book.html">
300
+ * controller: {{name}}<br />
301
+ * Book Id: {{params.bookId}}<br />
302
+ * </file>
303
+ *
304
+ * <file name="chapter.html">
305
+ * controller: {{name}}<br />
306
+ * Book Id: {{params.bookId}}<br />
307
+ * Chapter Id: {{params.chapterId}}
308
+ * </file>
309
+ *
310
+ * <file name="script.js">
311
+ * angular.module('ngRouteExample', ['ngRoute'])
312
+ *
313
+ * .controller('MainController', function($scope, $route, $routeParams, $location) {
314
+ * $scope.$route = $route;
315
+ * $scope.$location = $location;
316
+ * $scope.$routeParams = $routeParams;
317
+ * })
318
+ *
319
+ * .controller('BookController', function($scope, $routeParams) {
320
+ * $scope.name = "BookController";
321
+ * $scope.params = $routeParams;
322
+ * })
323
+ *
324
+ * .controller('ChapterController', function($scope, $routeParams) {
325
+ * $scope.name = "ChapterController";
326
+ * $scope.params = $routeParams;
327
+ * })
328
+ *
329
+ * .config(function($routeProvider, $locationProvider) {
330
+ * $routeProvider
331
+ * .when('/Book/:bookId', {
332
+ * templateUrl: 'book.html',
333
+ * controller: 'BookController',
334
+ * resolve: {
335
+ * // I will cause a 1 second delay
336
+ * delay: function($q, $timeout) {
337
+ * var delay = $q.defer();
338
+ * $timeout(delay.resolve, 1000);
339
+ * return delay.promise;
340
+ * }
341
+ * }
342
+ * })
343
+ * .when('/Book/:bookId/ch/:chapterId', {
344
+ * templateUrl: 'chapter.html',
345
+ * controller: 'ChapterController'
346
+ * });
347
+ *
348
+ * // configure html5 to get links working on jsfiddle
349
+ * $locationProvider.html5Mode(true);
350
+ * });
351
+ *
352
+ * </file>
353
+ *
354
+ * <file name="protractor.js" type="protractor">
355
+ * it('should load and compile correct template', function() {
356
+ * element(by.linkText('Moby: Ch1')).click();
357
+ * var content = element(by.css('[ng-view]')).getText();
358
+ * expect(content).toMatch(/controller\: ChapterController/);
359
+ * expect(content).toMatch(/Book Id\: Moby/);
360
+ * expect(content).toMatch(/Chapter Id\: 1/);
361
+ *
362
+ * element(by.partialLinkText('Scarlet')).click();
363
+ *
364
+ * content = element(by.css('[ng-view]')).getText();
365
+ * expect(content).toMatch(/controller\: BookController/);
366
+ * expect(content).toMatch(/Book Id\: Scarlet/);
367
+ * });
368
+ * </file>
369
+ * </example>
370
+ */
371
+
372
+ /**
373
+ * @ngdoc event
374
+ * @name $route#$routeChangeStart
375
+ * @eventType broadcast on root scope
376
+ * @description
377
+ * Broadcasted before a route change. At this point the route services starts
378
+ * resolving all of the dependencies needed for the route change to occur.
379
+ * Typically this involves fetching the view template as well as any dependencies
380
+ * defined in `resolve` route property. Once all of the dependencies are resolved
381
+ * `$routeChangeSuccess` is fired.
382
+ *
383
+ * @param {Object} angularEvent Synthetic event object.
384
+ * @param {Route} next Future route information.
385
+ * @param {Route} current Current route information.
386
+ */
387
+
388
+ /**
389
+ * @ngdoc event
390
+ * @name $route#$routeChangeSuccess
391
+ * @eventType broadcast on root scope
392
+ * @description
393
+ * Broadcasted after a route dependencies are resolved.
394
+ * {@link ngRoute.directive:ngView ngView} listens for the directive
395
+ * to instantiate the controller and render the view.
396
+ *
397
+ * @param {Object} angularEvent Synthetic event object.
398
+ * @param {Route} current Current route information.
399
+ * @param {Route|Undefined} previous Previous route information, or undefined if current is
400
+ * first route entered.
401
+ */
402
+
403
+ /**
404
+ * @ngdoc event
405
+ * @name $route#$routeChangeError
406
+ * @eventType broadcast on root scope
407
+ * @description
408
+ * Broadcasted if any of the resolve promises are rejected.
409
+ *
410
+ * @param {Object} angularEvent Synthetic event object
411
+ * @param {Route} current Current route information.
412
+ * @param {Route} previous Previous route information.
413
+ * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
414
+ */
415
+
416
+ /**
417
+ * @ngdoc event
418
+ * @name $route#$routeUpdate
419
+ * @eventType broadcast on root scope
420
+ * @description
421
+ *
422
+ * The `reloadOnSearch` property has been set to false, and we are reusing the same
423
+ * instance of the Controller.
424
+ */
425
+
426
+ var forceReload = false,
427
+ $route = {
428
+ routes: routes,
429
+
430
+ /**
431
+ * @ngdoc method
432
+ * @name $route#reload
433
+ *
434
+ * @description
435
+ * Causes `$route` service to reload the current route even if
436
+ * {@link ng.$location $location} hasn't changed.
437
+ *
438
+ * As a result of that, {@link ngRoute.directive:ngView ngView}
439
+ * creates new scope, reinstantiates the controller.
440
+ */
441
+ reload: function() {
442
+ forceReload = true;
443
+ $rootScope.$evalAsync(updateRoute);
444
+ }
445
+ };
446
+
447
+ $rootScope.$on('$locationChangeSuccess', updateRoute);
448
+
449
+ return $route;
450
+
451
+ /////////////////////////////////////////////////////
452
+
453
+ /**
454
+ * @param on {string} current url
455
+ * @param route {Object} route regexp to match the url against
456
+ * @return {?Object}
457
+ *
458
+ * @description
459
+ * Check if the route matches the current url.
460
+ *
461
+ * Inspired by match in
462
+ * visionmedia/express/lib/router/router.js.
463
+ */
464
+ function switchRouteMatcher(on, route) {
465
+ var keys = route.keys,
466
+ params = {};
467
+
468
+ if (!route.regexp) return null;
469
+
470
+ var m = route.regexp.exec(on);
471
+ if (!m) return null;
472
+
473
+ for (var i = 1, len = m.length; i < len; ++i) {
474
+ var key = keys[i - 1];
475
+
476
+ var val = 'string' == typeof m[i]
477
+ ? decodeURIComponent(m[i])
478
+ : m[i];
479
+
480
+ if (key && val) {
481
+ params[key.name] = val;
482
+ }
483
+ }
484
+ return params;
485
+ }
486
+
487
+ function updateRoute() {
488
+ var next = parseRoute(),
489
+ last = $route.current;
490
+
491
+ if (next && last && next.$$route === last.$$route
492
+ && angular.equals(next.pathParams, last.pathParams)
493
+ && !next.reloadOnSearch && !forceReload) {
494
+ last.params = next.params;
495
+ angular.copy(last.params, $routeParams);
496
+ $rootScope.$broadcast('$routeUpdate', last);
497
+ } else if (next || last) {
498
+ forceReload = false;
499
+ $rootScope.$broadcast('$routeChangeStart', next, last);
500
+ $route.current = next;
501
+ if (next) {
502
+ if (next.redirectTo) {
503
+ if (angular.isString(next.redirectTo)) {
504
+ $location.path(interpolate(next.redirectTo, next.params)).search(next.params)
505
+ .replace();
506
+ } else {
507
+ $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
508
+ .replace();
509
+ }
510
+ }
511
+ }
512
+
513
+ $q.when(next).
514
+ then(function() {
515
+ if (next) {
516
+ var locals = angular.extend({}, next.resolve),
517
+ template, templateUrl;
518
+
519
+ angular.forEach(locals, function(value, key) {
520
+ locals[key] = angular.isString(value) ?
521
+ $injector.get(value) : $injector.invoke(value);
522
+ });
523
+
524
+ if (angular.isDefined(template = next.template)) {
525
+ if (angular.isFunction(template)) {
526
+ template = template(next.params);
527
+ }
528
+ } else if (angular.isDefined(templateUrl = next.templateUrl)) {
529
+ if (angular.isFunction(templateUrl)) {
530
+ templateUrl = templateUrl(next.params);
531
+ }
532
+ templateUrl = $sce.getTrustedResourceUrl(templateUrl);
533
+ if (angular.isDefined(templateUrl)) {
534
+ next.loadedTemplateUrl = templateUrl;
535
+ template = $http.get(templateUrl, {cache: $templateCache}).
536
+ then(function(response) { return response.data; });
537
+ }
538
+ }
539
+ if (angular.isDefined(template)) {
540
+ locals['$template'] = template;
541
+ }
542
+ return $q.all(locals);
543
+ }
544
+ }).
545
+ // after route change
546
+ then(function(locals) {
547
+ if (next == $route.current) {
548
+ if (next) {
549
+ next.locals = locals;
550
+ angular.copy(next.params, $routeParams);
551
+ }
552
+ $rootScope.$broadcast('$routeChangeSuccess', next, last);
553
+ }
554
+ }, function(error) {
555
+ if (next == $route.current) {
556
+ $rootScope.$broadcast('$routeChangeError', next, last, error);
557
+ }
558
+ });
559
+ }
560
+ }
561
+
562
+
563
+ /**
564
+ * @returns {Object} the current active route, by matching it against the URL
565
+ */
566
+ function parseRoute() {
567
+ // Match a route
568
+ var params, match;
569
+ angular.forEach(routes, function(route, path) {
570
+ if (!match && (params = switchRouteMatcher($location.path(), route))) {
571
+ match = inherit(route, {
572
+ params: angular.extend({}, $location.search(), params),
573
+ pathParams: params});
574
+ match.$$route = route;
575
+ }
576
+ });
577
+ // No route matched; fallback to "otherwise" route
578
+ return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
579
+ }
580
+
581
+ /**
582
+ * @returns {string} interpolation of the redirect path with the parameters
583
+ */
584
+ function interpolate(string, params) {
585
+ var result = [];
586
+ angular.forEach((string||'').split(':'), function(segment, i) {
587
+ if (i === 0) {
588
+ result.push(segment);
589
+ } else {
590
+ var segmentMatch = segment.match(/(\w+)(.*)/);
591
+ var key = segmentMatch[1];
592
+ result.push(params[key]);
593
+ result.push(segmentMatch[2] || '');
594
+ delete params[key];
595
+ }
596
+ });
597
+ return result.join('');
598
+ }
599
+ }];
600
+ }
601
+
602
+ ngRouteModule.provider('$routeParams', $RouteParamsProvider);
603
+
604
+
605
+ /**
606
+ * @ngdoc service
607
+ * @name $routeParams
608
+ * @requires $route
609
+ *
610
+ * @description
611
+ * The `$routeParams` service allows you to retrieve the current set of route parameters.
612
+ *
613
+ * Requires the {@link ngRoute `ngRoute`} module to be installed.
614
+ *
615
+ * The route parameters are a combination of {@link ng.$location `$location`}'s
616
+ * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}.
617
+ * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched.
618
+ *
619
+ * In case of parameter name collision, `path` params take precedence over `search` params.
620
+ *
621
+ * The service guarantees that the identity of the `$routeParams` object will remain unchanged
622
+ * (but its properties will likely change) even when a route change occurs.
623
+ *
624
+ * Note that the `$routeParams` are only updated *after* a route change completes successfully.
625
+ * This means that you cannot rely on `$routeParams` being correct in route resolve functions.
626
+ * Instead you can use `$route.current.params` to access the new route's parameters.
627
+ *
628
+ * @example
629
+ * ```js
630
+ * // Given:
631
+ * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
632
+ * // Route: /Chapter/:chapterId/Section/:sectionId
633
+ * //
634
+ * // Then
635
+ * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
636
+ * ```
637
+ */
638
+ function $RouteParamsProvider() {
639
+ this.$get = function() { return {}; };
640
+ }
641
+
642
+ ngRouteModule.directive('ngView', ngViewFactory);
643
+ ngRouteModule.directive('ngView', ngViewFillContentFactory);
644
+
645
+
646
+ /**
647
+ * @ngdoc directive
648
+ * @name ngView
649
+ * @restrict ECA
650
+ *
651
+ * @description
652
+ * # Overview
653
+ * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by
654
+ * including the rendered template of the current route into the main layout (`index.html`) file.
655
+ * Every time the current route changes, the included view changes with it according to the
656
+ * configuration of the `$route` service.
657
+ *
658
+ * Requires the {@link ngRoute `ngRoute`} module to be installed.
659
+ *
660
+ * @animations
661
+ * enter - animation is used to bring new content into the browser.
662
+ * leave - animation is used to animate existing content away.
663
+ *
664
+ * The enter and leave animation occur concurrently.
665
+ *
666
+ * @scope
667
+ * @priority 400
668
+ * @param {string=} onload Expression to evaluate whenever the view updates.
669
+ *
670
+ * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll
671
+ * $anchorScroll} to scroll the viewport after the view is updated.
672
+ *
673
+ * - If the attribute is not set, disable scrolling.
674
+ * - If the attribute is set without value, enable scrolling.
675
+ * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated
676
+ * as an expression yields a truthy value.
677
+ * @example
678
+ <example name="ngView-directive" module="ngViewExample"
679
+ deps="angular-route.js;angular-animate.js"
680
+ animations="true" fixBase="true">
681
+ <file name="index.html">
682
+ <div ng-controller="MainCtrl as main">
683
+ Choose:
684
+ <a href="Book/Moby">Moby</a> |
685
+ <a href="Book/Moby/ch/1">Moby: Ch1</a> |
686
+ <a href="Book/Gatsby">Gatsby</a> |
687
+ <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
688
+ <a href="Book/Scarlet">Scarlet Letter</a><br/>
689
+
690
+ <div class="view-animate-container">
691
+ <div ng-view class="view-animate"></div>
692
+ </div>
693
+ <hr />
694
+
695
+ <pre>$location.path() = {{main.$location.path()}}</pre>
696
+ <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre>
697
+ <pre>$route.current.params = {{main.$route.current.params}}</pre>
698
+ <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre>
699
+ <pre>$routeParams = {{main.$routeParams}}</pre>
700
+ </div>
701
+ </file>
702
+
703
+ <file name="book.html">
704
+ <div>
705
+ controller: {{book.name}}<br />
706
+ Book Id: {{book.params.bookId}}<br />
707
+ </div>
708
+ </file>
709
+
710
+ <file name="chapter.html">
711
+ <div>
712
+ controller: {{chapter.name}}<br />
713
+ Book Id: {{chapter.params.bookId}}<br />
714
+ Chapter Id: {{chapter.params.chapterId}}
715
+ </div>
716
+ </file>
717
+
718
+ <file name="animations.css">
719
+ .view-animate-container {
720
+ position:relative;
721
+ height:100px!important;
722
+ position:relative;
723
+ background:white;
724
+ border:1px solid black;
725
+ height:40px;
726
+ overflow:hidden;
727
+ }
728
+
729
+ .view-animate {
730
+ padding:10px;
731
+ }
732
+
733
+ .view-animate.ng-enter, .view-animate.ng-leave {
734
+ -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
735
+ transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s;
736
+
737
+ display:block;
738
+ width:100%;
739
+ border-left:1px solid black;
740
+
741
+ position:absolute;
742
+ top:0;
743
+ left:0;
744
+ right:0;
745
+ bottom:0;
746
+ padding:10px;
747
+ }
748
+
749
+ .view-animate.ng-enter {
750
+ left:100%;
751
+ }
752
+ .view-animate.ng-enter.ng-enter-active {
753
+ left:0;
754
+ }
755
+ .view-animate.ng-leave.ng-leave-active {
756
+ left:-100%;
757
+ }
758
+ </file>
759
+
760
+ <file name="script.js">
761
+ angular.module('ngViewExample', ['ngRoute', 'ngAnimate'])
762
+ .config(['$routeProvider', '$locationProvider',
763
+ function($routeProvider, $locationProvider) {
764
+ $routeProvider
765
+ .when('/Book/:bookId', {
766
+ templateUrl: 'book.html',
767
+ controller: 'BookCtrl',
768
+ controllerAs: 'book'
769
+ })
770
+ .when('/Book/:bookId/ch/:chapterId', {
771
+ templateUrl: 'chapter.html',
772
+ controller: 'ChapterCtrl',
773
+ controllerAs: 'chapter'
774
+ });
775
+
776
+ // configure html5 to get links working on jsfiddle
777
+ $locationProvider.html5Mode(true);
778
+ }])
779
+ .controller('MainCtrl', ['$route', '$routeParams', '$location',
780
+ function($route, $routeParams, $location) {
781
+ this.$route = $route;
782
+ this.$location = $location;
783
+ this.$routeParams = $routeParams;
784
+ }])
785
+ .controller('BookCtrl', ['$routeParams', function($routeParams) {
786
+ this.name = "BookCtrl";
787
+ this.params = $routeParams;
788
+ }])
789
+ .controller('ChapterCtrl', ['$routeParams', function($routeParams) {
790
+ this.name = "ChapterCtrl";
791
+ this.params = $routeParams;
792
+ }]);
793
+
794
+ </file>
795
+
796
+ <file name="protractor.js" type="protractor">
797
+ it('should load and compile correct template', function() {
798
+ element(by.linkText('Moby: Ch1')).click();
799
+ var content = element(by.css('[ng-view]')).getText();
800
+ expect(content).toMatch(/controller\: ChapterCtrl/);
801
+ expect(content).toMatch(/Book Id\: Moby/);
802
+ expect(content).toMatch(/Chapter Id\: 1/);
803
+
804
+ element(by.partialLinkText('Scarlet')).click();
805
+
806
+ content = element(by.css('[ng-view]')).getText();
807
+ expect(content).toMatch(/controller\: BookCtrl/);
808
+ expect(content).toMatch(/Book Id\: Scarlet/);
809
+ });
810
+ </file>
811
+ </example>
812
+ */
813
+
814
+
815
+ /**
816
+ * @ngdoc event
817
+ * @name ngView#$viewContentLoaded
818
+ * @eventType emit on the current ngView scope
819
+ * @description
820
+ * Emitted every time the ngView content is reloaded.
821
+ */
822
+ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate'];
823
+ function ngViewFactory( $route, $anchorScroll, $animate) {
824
+ return {
825
+ restrict: 'ECA',
826
+ terminal: true,
827
+ priority: 400,
828
+ transclude: 'element',
829
+ link: function(scope, $element, attr, ctrl, $transclude) {
830
+ var currentScope,
831
+ currentElement,
832
+ previousElement,
833
+ autoScrollExp = attr.autoscroll,
834
+ onloadExp = attr.onload || '';
835
+
836
+ scope.$on('$routeChangeSuccess', update);
837
+ update();
838
+
839
+ function cleanupLastView() {
840
+ if(previousElement) {
841
+ previousElement.remove();
842
+ previousElement = null;
843
+ }
844
+ if(currentScope) {
845
+ currentScope.$destroy();
846
+ currentScope = null;
847
+ }
848
+ if(currentElement) {
849
+ $animate.leave(currentElement, function() {
850
+ previousElement = null;
851
+ });
852
+ previousElement = currentElement;
853
+ currentElement = null;
854
+ }
855
+ }
856
+
857
+ function update() {
858
+ var locals = $route.current && $route.current.locals,
859
+ template = locals && locals.$template;
860
+
861
+ if (angular.isDefined(template)) {
862
+ var newScope = scope.$new();
863
+ var current = $route.current;
864
+
865
+ // Note: This will also link all children of ng-view that were contained in the original
866
+ // html. If that content contains controllers, ... they could pollute/change the scope.
867
+ // However, using ng-view on an element with additional content does not make sense...
868
+ // Note: We can't remove them in the cloneAttchFn of $transclude as that
869
+ // function is called before linking the content, which would apply child
870
+ // directives to non existing elements.
871
+ var clone = $transclude(newScope, function(clone) {
872
+ $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () {
873
+ if (angular.isDefined(autoScrollExp)
874
+ && (!autoScrollExp || scope.$eval(autoScrollExp))) {
875
+ $anchorScroll();
876
+ }
877
+ });
878
+ cleanupLastView();
879
+ });
880
+
881
+ currentElement = clone;
882
+ currentScope = current.scope = newScope;
883
+ currentScope.$emit('$viewContentLoaded');
884
+ currentScope.$eval(onloadExp);
885
+ } else {
886
+ cleanupLastView();
887
+ }
888
+ }
889
+ }
890
+ };
891
+ }
892
+
893
+ // This directive is called during the $transclude call of the first `ngView` directive.
894
+ // It will replace and compile the content of the element with the loaded template.
895
+ // We need this directive so that the element content is already filled when
896
+ // the link function of another directive on the same element as ngView
897
+ // is called.
898
+ ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route'];
899
+ function ngViewFillContentFactory($compile, $controller, $route) {
900
+ return {
901
+ restrict: 'ECA',
902
+ priority: -400,
903
+ link: function(scope, $element) {
904
+ var current = $route.current,
905
+ locals = current.locals;
906
+
907
+ $element.html(locals.$template);
908
+
909
+ var link = $compile($element.contents());
910
+
911
+ if (current.controller) {
912
+ locals.$scope = scope;
913
+ var controller = $controller(current.controller, locals);
914
+ if (current.controllerAs) {
915
+ scope[current.controllerAs] = controller;
916
+ }
917
+ $element.data('$ngControllerController', controller);
918
+ $element.children().data('$ngControllerController', controller);
919
+ }
920
+
921
+ link(scope);
922
+ }
923
+ };
924
+ }
925
+
926
+
927
+ })(window, window.angular);