简体   繁体   English

Angular1.3:递归指令模板中的访问控制器功能?

[英]Angular1.3: Access controller function inside recursive directive template?

I can access controller functions once in my parent directive using the $parent operator, but this does not work in recursive child directives. 我可以使用$ parent运算符在父指令中访问控制器函数一次,但这在递归子指令中不起作用。 Below is an example of my code (I've tried to shorten it a bit for this): 下面是我的代码示例(为此,我尝试将其缩短一点):

//controller example (defined using controllerAs):--- //控制器示例(使用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:--- //'评论'指令.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));
        }
    }
  };
};

You can access parent controller's this with require . 您可以使用require访问父控制器的this

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. 但是,最好具有一个充当模型并保存控制器和指令数据的服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM