Dynamic NG-Controller Name

前端 未结 3 1134
不知归路
不知归路 2020-11-28 11:09

I want to dynamically specify a controller based on a config that we load. Something like this:

3条回答
  •  孤独总比滥情好
    2020-11-28 11:28

    I'm using it in ng-repeat, so this is improved code for loops and sub objects:

    Template:

    Directive:

    mainApp.directive('ngDynamicController', ['$compile', '$parse',function($compile, $parse) {
      return {
          scope: {
              name: '=ngDynamicController'
          },
          restrict: 'A',
          terminal: true,
          priority: 100000,
          link: function(scope, elem, attrs) {
              elem.attr('ng-controller', scope.name);
              elem.removeAttr('ng-dynamic-controller');
    
              $compile(elem)(scope);
          }
      };
    }]);
    

提交回复
热议问题