Dismiss
Announcing Stack Overflow Documentation

We started with Q&A. Technical documentation is next, and we need your help.

Whether you're a beginner or an experienced developer, you can contribute.

Sign up and start helping → Learn more about Documentation →

I have this controller with directive inside my html code. The directive have scope value I would like access from the parent controller and show in the html. Hope my example code give you a simple overview of what I'm trying to achieve.

I know this work using $rootScope.showvalue = 'pass text'; in the directive works but don't know if this is the best solution.

app.directive('customdir', [function() {
  return {
    restrict:   "E",
    scope:      {    
      showvalue: "="
    },
    link: function(scope, el, attrs) {
      scope.showvalue = 'pass text';

    }
  };  
}]);

app.controller('mycontroller', function($scope) {
  alert($scope.showvalue); 
});



<html>
     <div ng-controller="mycontroller">
        <custom-dir></custom-dir>

           /* Show scope value from custom dir */

          {{showvalue}}
     </div>
  </html>
share|improve this question
up vote 0 down vote accepted

Since you're binding the directive's isolate scope showvalue property via bidirectional binding, you can simple pass the parent scope property in as an attribute

<customdir showvalue="showvalue"></customdir>

<p>{{showvalue}}</p>

Demo ~ http://plnkr.co/edit/W5k0hgDElklseOvjwRsS?p=preview


If you want the HTML to be <custom-dir>, you'll need to rename your directive to 'customDir'.

share|improve this answer
    
For some reason only $rootScope.showvalue = 'pass text'; works. Maybe because the controller and directive are in 2 separate files – icode Aug 12 at 2:07
    
Did you look at the demo? It clearly works. Separating the files makes no difference – Phil Aug 12 at 2:23
    
Yes, your demo works fine clear example. Just my code its not working. I think maybe how the controller is setup. – icode Aug 12 at 2:47
    
Got it working now. The previous developer was using var crtlName = this; So to make it work I had to use {{crltName.somevalue}}. Thanks – icode Aug 12 at 3:56
  1. You can pass "showvalue" to the directive via attributes.
  2. You can set value through $parent property of directive scope. eg. scope.$parent.showvalue = 'pass text';
  3. You can use emit event to pass data from child (directive) to parent (controller).
  4. You can directly set value to the controller scope using shared scope. (Do not specify scope property in directive)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.