【问题标题】:Nesting Custom Directive with ng-repeat使用 ng-repeat 嵌套自定义指令
【发布时间】:2013-07-23 14:39:40
【问题描述】:

我是 AngularJS 的新手,

我正在尝试创建将 jQuery JScrollPane (JScrollpane.kelvinluck.com) 应用于 div 的自定义指令。

我有以下 html 代码:

<scrollPane> ------> WRONG
<div scroll-pane> -----> RIGHT
    <ul>
        <li data-ng-repeat="task in tasks">
            <div class="task-element">
                <div class="name">{{task.display_name}}</div>
                <div class="text">{{task.min_description}}</div>
            </div>
        </li>
    </ul>
</scrollPane>

以及以下指令:

angular.module('myApp', []).directive('scrollPane',function() {
return {
    restrict:'A',
    template: '<div></div>',
    link: function (scope, elm, attrs) {
    console.log("in directive");
    element.addClass('scroll-pane');
    element.jScrollPane({showArrows: true,autoReinitialise:true });
}};
});

主要问题是模板的 html 覆盖了整个 &lt;scrollPane&gt; 元素,并且 ng-repeat &lt;li&gt; 根本不显示并从最终的 html 中删除。

创建指令以用 html 包装内部 html 的正确方法是什么(在我的示例中,它将是 div 和 class='scroll-pane' ),我应该在哪里插入: $('.scroll-pane').jScrollPane();?

感谢帮助。

更新: 那么上面的代码变成了不工作, 问题出在 HTML 中,因为该指令应该在指令中带有一个限制:“A”。 (感谢http://www.befundoo.com/university/tutorials/angularjs-directives-tutorial/ 提示)

要应用 jScrollPane,我只是在指令内部使用

element.jScrollPane({showArrows: true,autoReinitialise:true }); 

一切都为我工作,但我有一个问题悬而未决: 对于某些 css 解决方法,我必须在 ng-repeat 中获取任务的长度才能为 div 设置固定高度。 当我调试时,我看到它还没有渲染, 怎么可能等到 ng-repeat 得到它的数据? (使用服务)。

【问题讨论】:

    标签: angularjs angularjs-directive angularjs-ng-repeat jquery-jscrollpane


    【解决方案1】:

    也许你正在寻找 transclude 函数

    angular.module('myApp', []).directive('scrollPane',function(){
    return {
        restrict:'E',
        transclude: true,
        template: '<div class='scroll-pane' ng-transclude></div>',
        link: function (scope, elm, attrs) {
            console.log("in directive");
        }
    };
    });
    

    这会将&lt;scroll-pane&gt; 的内容放在模板的div 中。

    我不知道该放在哪里$('.scroll-pane').jScrollPane(); 可能在链接功能和 angular.element(jquery selector here) ,角度包装。指令定义对象中的link函数实际上是一个post-link函数,它会在DOM被修改后运行。这是做额外 DOM 修改的安全地方。

    已编辑:此答案的某些部分与问题的当前版本不匹配。例如restrict: 'E'

    【讨论】:

      【解决方案2】:

      AnguarJS 指令有一个transclude 的概念。如果要将指令中包含的 html 包装到父 html 中,则需要使用 transclude

      所以你的指令定义会变成

      angular.module('myApp', []).directive('scrollPane',function(){
      return {
          restrict:'E',
          replace: true,
          transclude: true,
          template: '<div class='scroll-pane' ng-transclude></div>',
          link: function (scope, elm, attrs){
          console.log("in directive");
      }};
      
      });
      

      查看指令here的开发者指南

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多