【问题标题】:Is it possible to use a directive again inside its own template?是否可以在自己的模板中再次使用指令?
【发布时间】:2015-10-06 19:21:57
【问题描述】:

我正在尝试用 Angular 编写一个“cmets”指令来加载嵌套的 cmets(来自 Json 数据)并为子 cmets/回复重用相同的指令。

父 cmets 可以自行加载,但是当我尝试在其自己的模板中再次使用 'cmets' 指令显示子 cmets 时,应用程序会冻结,我必须将其关闭。

下面是我的一些代码:

app.html: ---

  <ul ng-repeat="comment in View2.postItems | limitTo: 10">

    <comments collection="comment"></comments>

  </ul>

cmets.html(指令):----

<li>      
  <span>
    {{ collection.data.commentText }}

    <ul ng-show="{{collection.data.replies}}"
        ng-repeat="comment in collection.data.replies.data.children">

      <!-**child comments: this line causes the app to freeze:**-->
      <comments collection="comment"></comments>

    </ul>

  </span>
</li>

cmets.js:---

var comments = function(){
  return {
    templateUrl : 'modules/comments/comments.html',
    restrict:'E',
    scope:{
      collection: '='
    },
    link: function(scope, element, attrs){

    }
  };
};

【问题讨论】:

    标签: javascript angularjs web-applications angularjs-directive javascript-framework


    【解决方案1】:

    您可以使用$compile 服务构建递归指令,以有条件地附加子指令。示例:(http://plnkr.co/edit/WpNp20DSjJhO412j3cSw?p=preview)

    function comment($compile) {
        return {
          template: '<span ng-bind="comment.text"></span>',
          link: function(scope, element) {
            if (angular.isArray(scope.comment.collection)) {
                  element.append($compile('<comments collection="comment.collection"></comments>')(scope));
            }
          }
        }
    }
    
    function comments(){
      return {
        template : '<ul><li ng-repeat="comment in collection"><comment></comment></li></ul>',
        scope:{
          collection: '='
        }
      };
    }
    

    【讨论】:

    • 谢谢,这有助于解决问题。
    猜你喜欢
    • 1970-01-01
    • 2016-02-08
    • 2018-04-23
    • 2023-03-23
    • 1970-01-01
    • 2017-08-13
    • 2018-09-14
    • 1970-01-01
    • 2016-01-17
    相关资源
    最近更新 更多