Search code examples
javascriptangularjsangularjs-directiveangularjs-ng-transclude

Can you use controller as syntax with directive/ng-transclude?


I'm using controller as syntax. Inside this scope, I have a directive which transcludes content that access this controller. That controller appears to be inaccessible from within the ng-transclude.

DEMO: http://plnkr.co/edit/ZYPCym2WQV43wh4R4nwI?p=preview

Is there a restraint from using controller as from within transcluded content?


Solution

  • I think stuff is getting mixed up b/c of the way you're using ng-controller with a directive. Unfortunately, I can't explain why, but the way you were setting up the controller seemed funny to me :)

    My thinking is, if you're putting ng-controller on an element that is a directive, you might as well make it a "directive controller" like this:

    function transcludeDirective() {
      return {
          restrict: 'E',
          transclude:true,
          scope: false,
          controller: DemoCtrl,
          controllerAs: 'DemoCtrlVM',
          template: '<div>'+
                      '<p>First name: <b>{{ DemoCtrlVM.first_name }}</b></p>'+
                      '<ng-transclude></ng-transclude>'+
                    '</div>'
      }
    }
    

    Be sure to remove the ng-controller="DemoCtrl as DemoCtrlVM" from the HTML. If you do this, it works as expected.

    This might not be what you want. Doing it your way, you could use a different controller with the directive, and doing it my way the controller is coupled to the directive...