2

我是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 覆盖了整个<scrollPane>元素,并且 ng-repeat<li>根本不显示并从最终的 html 中删除。

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

感谢帮助者。

更新:好吧,上面的代码不起作用,问题出在 HTML 中,因为指令应该在指令中带有一个限制:“A”。(感谢http://www.befundoo.com/university/tutorials/angularjs-directives-tutorial/tips

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

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

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

4

2 回答 2

3

也许您正在寻找 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");
    }
};
});

这会将 的内容放入<scroll-pane>div的模板中。

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

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

于 2013-07-24T08:39:23.927 回答
1

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

});

在此处查看指令的开发人员指南

于 2013-07-24T08:39:08.830 回答