Controller for access directives from relocated items

I have the following scenario: a transclude directive with an isolated area in which there is a controller:

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 look forward to accessing the directive controller from the moved items:

 <hello> <h1>Hello Directive</h1> <p>{{ hello }}</p> </hello> 

However, this is not possible. I tried to access hello using $parent and $$nextSibling .

Is there any solution for this scenario? I can not put the controller in a wrapper around the directive instance.

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

+6
source share
1 answer

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

More info here: Confused about Angularjs transcluded and isolate areas and bindings

Edit:

In the original example, the template expected the variable {{hello}} in the scope of the parent root, but it is actually in the scope of hello. In fact, an empty allocation region in a directive means that it will not receive any sphere variables from its parent. So, what has been done above is the route of the (non-existent) hello variable from the root region to the directive, and then sets the value.

For this to be illustrated, you can take a look at this: http://codepen.io/anon/pen/pJEqjq - you will see that the controller installs $rootScope.hello and it works. Although this is not recommended because relying on rootScope variables for different controllers can be messy.

+2
source

All Articles