Skip to content

Commit dd68190

Browse files
committed
feat($state): controllers can now be specified dynamically
Closes #389
1 parent 513865a commit dd68190

File tree

2 files changed

+23
-2
lines changed

2 files changed

+23
-2
lines changed

src/state.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -504,7 +504,13 @@ function $StateProvider( $urlRouterProvider, $urlMatcherFactory, $
504504

505505
promises.push($resolve.resolve(injectables, locals, dst.resolve, state).then(function (result) {
506506
// References to the controller (only instantiated at link time)
507-
result.$$controller = view.controller;
507+
if (isFunction(view.controllerProvider)) {
508+
result.$$controller = $injector.invoke(
509+
view.controllerProvider, null, angular.extend({}, injectables, locals)
510+
);
511+
} else {
512+
result.$$controller = view.controller;
513+
}
508514
// Provide access to the state itself for internal use
509515
result.$$state = state;
510516
dst[name] = result;

test/stateSpec.js

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
describe('state', function () {
22

3-
var stateProvider, locationProvider, templateParams;
3+
var stateProvider, locationProvider, templateParams, ctrlName;
44

55
beforeEach(module('ui.router', function($locationProvider) {
66
locationProvider = $locationProvider;
@@ -59,6 +59,14 @@ describe('state', function () {
5959
return "/templates/" + params.item + ".html";
6060
}
6161
})
62+
.state('dynamicController', {
63+
url: "/dynamic/:type",
64+
template: "test",
65+
controllerProvider: function($stateParams) {
66+
ctrlName = $stateParams.type + "Controller";
67+
return ctrlName;
68+
}
69+
})
6270
.state('home.redirect', {
6371
url: "redir",
6472
onEnter: function($state) {
@@ -382,6 +390,12 @@ describe('state', function () {
382390
var err = "Could not resolve '^.Z' from state 'DD'";
383391
expect(function() { $state.transitionTo("^.Z", null, { relative: $state.$current }); }).toThrow(err);
384392
}));
393+
394+
it('uses the controllerProvider to get controller dynamically', inject(function ($state, $q) {
395+
$state.transitionTo('dynamicController', { type: "Acme" });
396+
$q.flush();
397+
expect(ctrlName).toEqual("AcmeController");
398+
}));
385399
});
386400

387401
describe('.go()', function () {
@@ -595,6 +609,7 @@ describe('state', function () {
595609
'about.person.item',
596610
'about.sidebar',
597611
'about.sidebar.item',
612+
'dynamicController',
598613
'first',
599614
'home',
600615
'home.item',

0 commit comments

Comments
 (0)