Dynamic NG-Controller Name

前端 未结 3 1112
不知归路
不知归路 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:47

    What you want to do is have another directive run before anything else is called, get the controller name from some model remove the new directive and add the ng-controller directive, then re-compile the element.

    That looks like this:

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

    Then you could use it in your template, like so:

    {{tyler}}

    with a controller like this:

    global.controller('blankCtrl',['$scope',function(tyler){
        tyler.tyler = 'tyler';
        tyler.tyler = 'chameleon';
    }]);
    

    There's probably a way of interpolating the value ($interpolate) of the dynamic-ctrl instead of parsing it ($parse), but I couldn't get it to work for some reason.

提交回复
热议问题