Angular $compile with required controller

烂漫一生 提交于 2019-12-03 11:00:59

I've just had a similar issue, and the solution seems to be to first add the element to the parent, and then compile it.

.directive('item', function($compile) {
  return {
    template:'<li><a ng-click="addSubList()">Create Another List</a></li>',
    require: '^parent',
    replace: true,
    link: function(scope, element, attrs, parentCtrl) {

      scope.addSubList = function() {
        var sublist = angular.element('<ul list>');
        element.find('a').append(sublist);
        $compile(sublist)(scope);
      };

    }
  };
});

See this Plunker: http://plnkr.co/edit/dASASrFbtXSMCRZKRAj5?p=preview

Tomer

For future reference, here is the solution:

On the $compile function the required controller can be passed as the transcluded controller:

$compile(template)(scope, undefined, {transcludeControllers: injectedCtrl})

Where the "injectedCtrl" is the object which lists controllers the directive expects, for example if you require: '^dad', then transcludeControllers look like this:

 transcludeControllers: {
        dad: { //name of controller in 'require' statement
          instance: vm //instance of controller
        }
      }

See this example: https://jsfiddle.net/qq4gqn6t/11/


Thats it!

Zhu
$compile(angular.element("< list>< /list >"))(scope)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!