I'm trying to write a generalized route in my application and resolve the view and controller names on the fly based on the route params.
I have the following code that works:
$stateProvider.state('default', angularAMD.route({
url: '/:module/:action?id',
templateUrl: function (params) {
var module = params.module;
var action = module + params.action.charAt(0).toUpperCase()
+ params.action.substr(1);
return 'app/views/' + module + '/' + action + 'View.html';
},
controller: 'userController',
}));
However, I'm unable to figure out a way to resolve the controller name dynamically. I tried using resolve
as described here, but ui-router seems to handle resolve differently than angular-route.
Any pointers?
EDIT: I've already tried using controllerProvider
but it doesn't work for me (for instance, the following code just returns a hard coded controller name to test whether it actually works):
controllerProvider: function () {
return 'userController';
}
Gives me the following error:
Error: [ng:areq] Argument 'userController' is not a function, got undefined
http://errors.angularjs.org/1.3.3/ng/areq?p0=userController&p1=not%20aNaNunction%2C%20got%20undefined
This is a link to working plunker.
solution
We need two features of the UI-Router:
angularAMD - main.js definition
This would be our main.js, which contains smart conversion controllerName - controllerPath:
controllers:
app.js
Firstly we would need some method converting the param (e.g. id) into controller name. For our test purposes let's use this naive implementation:
.state()
And that would be finally our state definition
Check it here, in this working example
documentation
As documented here: $stateProvider, for a
state(name, stateConfig)
we can usecontroller
andcontrollerProvider
. Some extract from documentation:controllerProvider
...
controller
(optional) stringfunctioncontrollerProvider
(optional) function...
resolve
resolve
(optional) objectI.e. let's use
controllerProvider
:In case, that you managed to get here, maybe you'd like to check another similar solution with RequireJS - angular-ui-router with requirejs, lazy loading of controller