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
  1. Replacing  attribute
  2. $parse getting variable value
  3. $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

Popular posts from this blog

VS2017-Build fail-FindDependenciesOfExternallyResolvedReferences

IIS Block IP Setting

VS2017.15.8.4 Error fixed