ng-controller dynamic load
Basically, We use the ng-controller will declare as below.
Now, We have an issue is that the ng-controller need to be injected dynamically, So that we can use different controllers, e.g.
ng-controller="vm.GetConroller() as vm"
ps: This code snippet cannot be run.
Workaround-Directive
- Replacing attribute
- $parse getting variable value
- $compile turn into the HTML we need. e.g.:ng-controller='SecondController as vm'
app.directive('sgDynamicCtrl', ['$compile', '$parse', function ($compile, $parse) {
return {
restrict: 'A',
terminal: true,
priority: 100000,
link: function (scope, elem) {
var name = $parse(elem.attr('sg-dynamic-ctrl'))(scope);
elem.removeAttr('sg-dynamic-ctrl');
elem.attr('ng-controller', name);
$compile(elem)(scope);
}
};
}]);
How to use
Reference