Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access directive's controller from transcluded elements

I have the following scenario: A transclude directive with isolated scope which has a controller attached in it:

angular.module('app', [])
.directive('hello', function() {

   return {  

     controller: function($scope) {
       $scope.hello = "Hello World";
     },

     restrict: 'E',
     replace: true,
     transclude: true,
     template: '<div class="hello" ng-transclude></div>',
     scope: {}
   };

});

I'm looking forward to access the directive's controller from the transcluded elements:

<hello>
  <h1>Hello Directive</h1>

  <p>{{ hello }}</p>
</hello>

However this doesn't seems to be possible. I tried accessing hello with $parent and $$nextSibling.

Is there any solution to this scenario? I'm not able to put the controller in wrapper around the directive instance.

I created a codepen to demonstrate this behaviour: http://codepen.io/jviotti/pen/ktpbE?editors=101

like image 333
jviotti Avatar asked Apr 08 '14 15:04

jviotti


1 Answers

You need to pass the variable into the hello directive as a binding, and also include it as part of the isolate scope: http://codepen.io/anon/pen/yoCkp

More information here: Confused about Angularjs transcluded and isolate scopes & bindings

Edit:

In the original example, the template expected the {{ hello }} variable in the parent root scope, but it is actually in the hello directive scope. In fact, the empty isolate scope in the directive means that it will not get any scope variables from its parent. So what the above change does is route the (non-existent) hello variable from the root scope into the directive, and then sets the value.

To further illustrate this, you can take a look at this: http://codepen.io/anon/pen/pJEqjq - you will see that the controller is setting $rootScope.hello and it works as well. Though this is not advised because relying on the rootScope variables across different controllers can get messy.

like image 184
goldins Avatar answered Sep 28 '22 08:09

goldins