You could try writing custom directive:
.directive("ngDynamicController",function($compile){
return {
terminal: true,
priority: 1000,
link:function(scope,element,attr){
var controllerProperty = scope[attr.ngDynamicController];
element.attr('ng-controller', controllerProperty);
element.removeAttr("ng-dynamic-controller");
$compile(element)(scope);
}
}
})
If you need more information why we have to add terminal: true
and priority: 1000
. Check out my answer to this question: Add directives from directive in AngularJS
You could try injecting it as a value:
angular.module('app', [])
.value('InnerCtrl',InnerCtrlAsLocalVariable)
.controller('OuterCtrl', ['$scope','InnerCtrl',
function($scope, InnerCtrl) { //inject the value into the function
$scope.dynamicCtrl = InnerCtrl;
}
])
Or use $injector to resolve dynamically:
var InnerCtrlAsLocalVariable = ['$scope',
function($scope) {
$scope.message = 'from controller defined in module - want';
}
]
angular.module('app', [])
.value('InnerCtrl',InnerCtrlAsLocalVariable)
.controller('OuterCtrl', ['$scope','$injector',
function($scope, $injector) { //inject the $injector service.
// resolve the value dynamically
$scope.dynamicCtrl = $injector.get('InnerCtrl');
}
])
.controller('InnerCtrlFromModule', InnerCtrlAsLocalVariable)
You can use $controller
service to create the controller instance dynamically, from that instance we can retrieve the constructor function using constructor
property
angular.module('app', [])
.controller('OuterCtrl', ['$scope','$controller',
function(scope, $controller) {
scope.dynamicCtrl = $controller('InnerCtrlFromModule',{$scope:scope.$new()}).constructor;
}
])
.controller('InnerCtrlFromModule',['$scope', function($scope) {
$scope.message = 'from controller defined in module - want';
}])