0

I can access controller functions once in my parent directive using the $parent operator, but this does not work in recursive child directives. Below is an example of my code (I've tried to shorten it a bit for this):

//controller example (defined using controllerAs):---

  var View2Ctrl = function(){

      //function i am trying to access:
      this.getNumber = function(){
        return 5;
      }
.
.
.
angular.controller('View2Ctrl',............

//'comments' directive template:--

<li>
      <!-- I'm trying to access the function in here: -->
      <!-- below line works just once here, does not load in recursive child directives below:  -->
      <strong> Number: </strong> {{ $parent.View2Ctrl.getNumber() }}

          <!-- below line gets replaced with a recursive child directive again -->
          <span class="comments-placeholder" ></span>     
</li>

//'comments' directive.js:---

var comments = function($compile){
  return {
    templateUrl : 'modules/comments/commentsDirective.html',
    restrict:'E',
    scope:{
      collection: '='
    },
    link: function(scope, element, attrs){
        if(scope.collection.data.replies){
          var elementResult = angular.element(element[0].getElementsByClassName('comments-placeholder'));

          elementResult.replaceWith($compile('<ul ng-repeat="comment in collection.data.replies.data.children><comments collection="comment"></comments></ul>')(scope));
        }
    }
  };
};
1
  • pass the function as attribute to directive scope Commented Jul 17, 2015 at 20:33

1 Answer 1

1

You can access parent controller's this with require.

var comments = function($compile){
  return {
    ...
    require: '^ngController',
    link: function(scope, element, attrs, ctrl){
       $scope.number = ctrl.getNumber();
    }
  };
};

But it is always better to have a service that acts as a model and holds data for both controller and directives.

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

Comments

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.