refactor(angular_1_router): use directives for route targets

BREAKING CHANGE:

Previously, route configuration took a controller constructor function as the value of
`component` in a route definition:

```
$route.config([
  { route: '/', component: MyController }
])
```

Based on the name of the controller, we used to use a componentMapper service to
determine what template to pair with each controller, how to bind the instance to
the $scope.

To make the 1.x router more semantically alligned with Angular 2, we now route to a directive.
Thus a route configuration takes a normalized directive name:

```
$route.config([
  { route: '/', component: 'myDirective' }
])
```

BREAKING CHANGE:

In order to avoid name collisions, lifecycle hooks are now prefixed with `$`. Before:

```
MyController.prototype.onActivate = ...
```

After:

```
MyController.prototype.$onActivate = ...
```

Same for `$canActivate` (which now lives on the directive factory function),
`$canDeactivate`, `$canReuse`, and `$onDeactivate` hooks.
This commit is contained in:
Brian Ford
2015-09-18 15:53:50 -07:00
parent 6e0ca7f39a
commit 5205a9e65f
12 changed files with 547 additions and 724 deletions

View File

@ -1,53 +1,45 @@
'use strict';
describe('ngOutlet', function () {
describe('Navigation lifecycle', function () {
var elt,
$compile,
$rootScope,
$router,
$templateCache,
$controllerProvider,
$componentMapperProvider;
var OneController, TwoController, UserController;
function instructionFor(componentType) {
return jasmine.objectContaining({componentType: componentType});
}
$compile,
$rootScope,
$router,
$compileProvider;
beforeEach(function () {
module('ng');
module('ngComponentRouter');
module(function (_$controllerProvider_, _$componentMapperProvider_) {
$controllerProvider = _$controllerProvider_;
$componentMapperProvider = _$componentMapperProvider_;
module(function (_$compileProvider_) {
$compileProvider = _$compileProvider_;
});
inject(function (_$compile_, _$rootScope_, _$router_, _$templateCache_) {
inject(function (_$compile_, _$rootScope_, _$router_) {
$compile = _$compile_;
$rootScope = _$rootScope_;
$router = _$router_;
$templateCache = _$templateCache_;
});
UserController = registerComponent('user', '<div>hello {{user.name}}</div>', function ($routeParams) {
this.name = $routeParams.name;
registerComponent('oneCmp', {
template: '<div>{{oneCmp.number}}</div>',
controller: function () {this.number = 'one'}
});
registerComponent('twoCmp', {
template: '<div><a ng-link="[\'/Two\']">{{twoCmp.number}}</a></div>',
controller: function () {this.number = 'two'}
});
OneController = registerComponent('one', '<div>{{one.number}}</div>', boringController('number', 'one'));
TwoController = registerComponent('two', '<div>{{two.number}}</div>', boringController('number', 'two'));
});
it('should run the activate hook of controllers', function () {
var spy = jasmine.createSpy('activate');
var activate = registerComponent('activate', '', {
onActivate: spy
registerComponent('activateCmp', {
template: '<p>hello</p>',
$onActivate: spy
});
$router.config([
{ path: '/a', component: activate }
{ path: '/a', component: 'activateCmp' }
]);
compile('<div>outer { <div ng-outlet></div> }</div>');
@ -60,31 +52,32 @@ describe('ngOutlet', function () {
it('should pass instruction into the activate hook of a controller', function () {
var spy = jasmine.createSpy('activate');
var UserController = registerComponent('user', '', {
onActivate: spy
registerComponent('userCmp', {
$onActivate: spy
});
$router.config([
{ path: '/user/:name', component: UserController }
{ path: '/user/:name', component: 'userCmp' }
]);
compile('<div ng-outlet></div>');
$router.navigateByUrl('/user/brian');
$rootScope.$digest();
expect(spy).toHaveBeenCalledWith(instructionFor(UserController), undefined);
expect(spy).toHaveBeenCalledWith(instructionFor('userCmp'), undefined);
});
it('should pass previous instruction into the activate hook of a controller', function () {
var spy = jasmine.createSpy('activate');
var activate = registerComponent('activate', '', {
onActivate: spy
var activate = registerComponent('activateCmp', {
template: 'hi',
$onActivate: spy
});
$router.config([
{ path: '/user/:name', component: OneController },
{ path: '/post/:id', component: activate }
{ path: '/user/:name', component: 'oneCmp' },
{ path: '/post/:id', component: 'activateCmp' }
]);
compile('<div ng-outlet></div>');
@ -92,19 +85,21 @@ describe('ngOutlet', function () {
$rootScope.$digest();
$router.navigateByUrl('/post/123');
$rootScope.$digest();
expect(spy).toHaveBeenCalledWith(instructionFor(activate),
instructionFor(OneController));
expect(spy).toHaveBeenCalledWith(instructionFor('activateCmp'),
instructionFor('oneCmp'));
});
it('should inject $scope into the controller constructor', function () {
var injectedScope;
var UserController = registerComponent('user', '', function ($scope) {
injectedScope = $scope;
registerComponent('userCmp', {
template: '',
controller: function ($scope) {
injectedScope = $scope;
}
});
$router.config([
{ path: '/user', component: UserController }
{ path: '/user', component: 'userCmp' }
]);
compile('<div ng-outlet></div>');
@ -117,13 +112,13 @@ describe('ngOutlet', function () {
it('should run the deactivate hook of controllers', function () {
var spy = jasmine.createSpy('deactivate');
var deactivate = registerComponent('deactivate', '', {
onDeactivate: spy
registerComponent('deactivateCmp', {
$onDeactivate: spy
});
$router.config([
{ path: '/a', component: deactivate },
{ path: '/b', component: OneController }
{ path: '/a', component: 'deactivateCmp' },
{ path: '/b', component: 'oneCmp' }
]);
compile('<div ng-outlet></div>');
@ -137,13 +132,13 @@ describe('ngOutlet', function () {
it('should pass instructions into the deactivate hook of controllers', function () {
var spy = jasmine.createSpy('deactivate');
var deactivate = registerComponent('deactivate', '', {
onDeactivate: spy
registerComponent('deactivateCmp', {
$onDeactivate: spy
});
$router.config([
{ path: '/user/:name', component: deactivate },
{ path: '/post/:id', component: OneController }
{ path: '/user/:name', component: 'deactivateCmp' },
{ path: '/post/:id', component: 'oneCmp' }
]);
compile('<div ng-outlet></div>');
@ -151,29 +146,29 @@ describe('ngOutlet', function () {
$rootScope.$digest();
$router.navigateByUrl('/post/123');
$rootScope.$digest();
expect(spy).toHaveBeenCalledWith(instructionFor(OneController),
instructionFor(deactivate));
expect(spy).toHaveBeenCalledWith(instructionFor('oneCmp'),
instructionFor('deactivateCmp'));
});
it('should run the deactivate hook before the activate hook', function () {
var log = [];
var activate = registerComponent('activate', '', {
onActivate: function () {
registerComponent('activateCmp', {
$onActivate: function () {
log.push('activate');
}
});
var deactivate = registerComponent('deactivate', '', {
onDeactivate: function () {
registerComponent('deactivateCmp', {
$onDeactivate: function () {
log.push('deactivate');
}
});
$router.config([
{ path: '/a', component: deactivate },
{ path: '/b', component: activate }
{ path: '/a', component: 'deactivateCmp' },
{ path: '/b', component: 'activateCmp' }
]);
compile('outer { <div ng-outlet></div> }');
@ -185,25 +180,32 @@ describe('ngOutlet', function () {
expect(log).toEqual(['deactivate', 'activate']);
});
it('should reuse a component when the canReuse hook returns true', function () {
var log = [];
var cmpInstanceCount = 0;
function ReuseCmp() {
cmpInstanceCount++;
this.canReuse = function () {
return true;
};
this.onReuse = function (next, prev) {
log.push('reuse: ' + prev.urlPath + ' -> ' + next.urlPath);
};
}
ReuseCmp.$routeConfig = [{path: '/a', component: OneController}, {path: '/b', component: TwoController}];
registerComponent('reuse', 'reuse {<ng-outlet></ng-outlet>}', ReuseCmp);
registerComponent('reuseCmp', {
template: 'reuse {<ng-outlet></ng-outlet>}',
$routeConfig: [
{path: '/a', component: 'oneCmp'},
{path: '/b', component: 'twoCmp'}
],
controller: ReuseCmp,
$canReuse: function () {
return true;
},
$onReuse: function (next, prev) {
log.push('reuse: ' + prev.urlPath + ' -> ' + next.urlPath);
}
});
$router.config([
{ path: '/on-reuse/:number/...', component: ReuseCmp }
{ path: '/on-reuse/:number/...', component: 'reuseCmp' },
{ path: '/two', component: 'twoCmp', as: 'Two'}
]);
compile('outer { <div ng-outlet></div> }');
@ -227,18 +229,25 @@ describe('ngOutlet', function () {
function NeverReuseCmp() {
cmpInstanceCount++;
this.canReuse = function () {
return false;
};
this.onReuse = function (next, prev) {
log.push('reuse: ' + prev.urlPath + ' -> ' + next.urlPath);
};
}
NeverReuseCmp.$routeConfig = [{path: '/a', component: OneController}, {path: '/b', component: TwoController}];
registerComponent('reuse', 'reuse {<ng-outlet></ng-outlet>}', NeverReuseCmp);
registerComponent('reuseCmp', {
template: 'reuse {<ng-outlet></ng-outlet>}',
$routeConfig: [
{path: '/a', component: 'oneCmp'},
{path: '/b', component: 'twoCmp'}
],
controller: NeverReuseCmp,
$canReuse: function () {
return false;
},
$onReuse: function (next, prev) {
log.push('reuse: ' + prev.urlPath + ' -> ' + next.urlPath);
}
});
$router.config([
{ path: '/never-reuse/:number/...', component: NeverReuseCmp }
{ path: '/never-reuse/:number/...', component: 'reuseCmp' },
{ path: '/two', component: 'twoCmp', as: 'Two'}
]);
compile('outer { <div ng-outlet></div> }');
@ -256,17 +265,17 @@ describe('ngOutlet', function () {
});
// TODO: need to solve getting ahold of canActivate hook
it('should not activate a component when canActivate returns false', function () {
var canActivateSpy = jasmine.createSpy('canActivate').and.returnValue(false);
var spy = jasmine.createSpy('activate');
var activate = registerComponent('activate', '', {
canActivate: function () {
return false;
},
onActivate: spy
registerComponent('activateCmp', {
$canActivate: canActivateSpy,
$onActivate: spy
});
$router.config([
{ path: '/a', component: activate }
{ path: '/a', component: 'activateCmp' }
]);
compile('outer { <div ng-outlet></div> }');
@ -279,38 +288,40 @@ describe('ngOutlet', function () {
it('should activate a component when canActivate returns true', function () {
var spy = jasmine.createSpy('activate');
var activate = registerComponent('activate', 'hi', {
canActivate: function () {
return true;
},
onActivate: spy
var activateSpy = jasmine.createSpy('activate');
var canActivateSpy = jasmine.createSpy('canActivate').and.returnValue(true);
registerComponent('activateCmp', {
template: 'hi',
$canActivate: canActivateSpy,
$onActivate: activateSpy
});
$router.config([
{ path: '/a', component: activate }
{ path: '/a', component: 'activateCmp' }
]);
compile('<div ng-outlet></div>');
$router.navigateByUrl('/a');
$rootScope.$digest();
expect(spy).toHaveBeenCalled();
expect(canActivateSpy).toHaveBeenCalled();
expect(activateSpy).toHaveBeenCalled();
expect(elt.text()).toBe('hi');
});
it('should activate a component when canActivate returns a resolved promise', inject(function ($q) {
var spy = jasmine.createSpy('activate');
var activate = registerComponent('activate', 'hi', {
canActivate: function () {
registerComponent('activateCmp', {
template: 'hi',
$canActivate: function () {
return $q.when(true);
},
onActivate: spy
$onActivate: spy
});
$router.config([
{ path: '/a', component: activate }
{ path: '/a', component: 'activateCmp' }
]);
compile('<div ng-outlet></div>');
@ -324,33 +335,38 @@ describe('ngOutlet', function () {
it('should inject into the canActivate hook of controllers', inject(function ($http) {
var spy = jasmine.createSpy('canActivate').and.returnValue(true);
var activate = registerComponent('activate', '', {
canActivate: spy
registerComponent('activateCmp', {
$canActivate: spy
});
spy.$inject = ['$routeParams', '$http'];
spy.$inject = ['$nextInstruction', '$http'];
$router.config([
{ path: '/user/:name', component: activate }
{ path: '/user/:name', component: 'activateCmp' }
]);
compile('<div ng-outlet></div>');
$router.navigateByUrl('/user/brian');
$rootScope.$digest();
expect(spy).toHaveBeenCalledWith({name: 'brian'}, $http);
expect(spy).toHaveBeenCalled();
var args = spy.calls.mostRecent().args;
expect(args[0].params).toEqual({name: 'brian'});
expect(args[1]).toBe($http);
}));
it('should not navigate when canDeactivate returns false', function () {
var activate = registerComponent('activate', 'hi', {
canDeactivate: function () {
registerComponent('activateCmp', {
template: 'hi',
$canDeactivate: function () {
return false;
}
});
$router.config([
{ path: '/a', component: activate },
{ path: '/b', component: OneController }
{ path: '/a', component: 'activateCmp' },
{ path: '/b', component: 'oneCmp' }
]);
compile('outer { <div ng-outlet></div> }');
@ -365,15 +381,16 @@ describe('ngOutlet', function () {
it('should navigate when canDeactivate returns true', function () {
var activate = registerComponent('activate', 'hi', {
canDeactivate: function () {
registerComponent('activateCmp', {
template: 'hi',
$canDeactivate: function () {
return true;
}
});
$router.config([
{ path: '/a', component: activate },
{ path: '/b', component: OneController }
{ path: '/a', component: 'activateCmp' },
{ path: '/b', component: 'oneCmp' }
]);
compile('outer { <div ng-outlet></div> }');
@ -389,15 +406,16 @@ describe('ngOutlet', function () {
it('should activate a component when canActivate returns true', function () {
var spy = jasmine.createSpy('activate');
var activate = registerComponent('activate', 'hi', {
canActivate: function () {
registerComponent('activateCmp', {
template: 'hi',
$canActivate: function () {
return true;
},
onActivate: spy
$onActivate: spy
});
$router.config([
{ path: '/a', component: activate }
{ path: '/a', component: 'activateCmp' }
]);
compile('<div ng-outlet></div>');
@ -411,13 +429,13 @@ describe('ngOutlet', function () {
it('should pass instructions into the canDeactivate hook of controllers', function () {
var spy = jasmine.createSpy('canDeactivate').and.returnValue(true);
var deactivate = registerComponent('deactivate', '', {
canDeactivate: spy
registerComponent('deactivateCmp', {
$canDeactivate: spy
});
$router.config([
{ path: '/user/:name', component: deactivate },
{ path: '/post/:id', component: OneController }
{ path: '/user/:name', component: 'deactivateCmp' },
{ path: '/post/:id', component: 'oneCmp' }
]);
compile('<div ng-outlet></div>');
@ -425,43 +443,36 @@ describe('ngOutlet', function () {
$rootScope.$digest();
$router.navigateByUrl('/post/123');
$rootScope.$digest();
expect(spy).toHaveBeenCalledWith(instructionFor(OneController),
instructionFor(deactivate));
expect(spy).toHaveBeenCalledWith(instructionFor('oneCmp'),
instructionFor('deactivateCmp'));
});
function registerComponent(name, template, config) {
var Ctrl;
if (!template) {
template = '';
}
if (!config) {
Ctrl = function () {};
} else if (angular.isArray(config)) {
Ctrl = function () {};
Ctrl.annotations = [new angular.annotations.RouteConfig(config)];
} else if (typeof config === 'function') {
Ctrl = config;
} else {
Ctrl = function () {};
if (config.canActivate) {
Ctrl.$canActivate = config.canActivate;
delete config.canActivate;
function registerComponent(name, options) {
var controller = options.controller || function () {};
['$onActivate', '$onDeactivate', '$onReuse', '$canReuse', '$canDeactivate'].forEach(function (hookName) {
if (options[hookName]) {
controller.prototype[hookName] = options[hookName];
}
Ctrl.prototype = config;
});
function factory() {
return {
template: options.template || '',
controllerAs: name,
controller: controller
};
}
$controllerProvider.register(componentControllerName(name), Ctrl);
put(name, template);
return Ctrl;
}
function boringController(model, value) {
return function () {
this[model] = value;
};
}
if (options.$canActivate) {
factory.$canActivate = options.$canActivate;
}
if (options.$routeConfig) {
factory.$routeConfig = options.$routeConfig;
}
function put(name, template) {
$templateCache.put(componentTemplatePath(name), [200, template, {}]);
$compileProvider.directive(name, factory);
}
function compile(template) {
@ -469,4 +480,8 @@ describe('ngOutlet', function () {
$rootScope.$digest();
return elt;
}
function instructionFor(componentType) {
return jasmine.objectContaining({componentType: componentType});
}
});