1

When adding a controller to a element directive, for example:

.directive('hello', function() {

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

});

I'm unable to access the scope of the controller:

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


<hello ng-controller="HelloCtrl">
  <h1>Hello Directive</h1>

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

In this case {{ hello }} is undefined. The directive doesn't create a child nor an isolated scope. I also tried accessing the property with {{ $parent.hello }}.

What is happening here?

I created a CodePen to demonstrate this behaviour: http://codepen.io/jviotti/pen/ktpbE

1 Answer 1

1

Per the docs...

transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside.

Therefore you need to move the ng-controller="HelloCtrl" declaration to an element higher up in scope.

Here is your CodePen fixed http://codepen.io/anon/pen/BjKHG

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any other way to accomplish this without putting the controller in an element higher in the scope?
You could just assign the controller in the directive definition using the controller property

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.