Angular1.3:递归指令模板中的访问控制器函数

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

本文关键字:访问 访问控制 控制器 函数 递归 指令 Angular1      更新时间:2023-09-26

我可以使用$parent操作符在父指令中访问一次控制器函数,但这在递归子指令中不起作用。下面是我的代码示例(我试着把它缩短一点):

//控制器示例(使用controllerAs定义):——

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

//'comments'指令模板:——

<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));
        }
    }
  };
};

可以通过require访问父控制器的this

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

但是最好有一个服务作为模型,为控制器和指令保存数据。