NG-Repeat后运行指令

时间:2014-08-27 20:39:24

标签: javascript html angularjs

所以我希望尽可能将我的插件库移到Angular上以保持一致。我遇到的问题是在其子代的任何指令运行之后运行指令。

为了明确一点,我们的目标是让我们的集成商(仅限CSS / HTML的团队成员)轻松地为项目添加动态功能,只需使用功能标记即可。目前,他们通过data-features属性执行此操作。例如,对于图像滑块,他们可能会使用data-features="imageSlider"属性标记UL,以使该UL成为滑块。

沿着这些方向,我正在努力将图像滑块模块移动到角度。我希望我的集成商能够编写如下内容:

<ul image-slider>
    <li slide>
         My Slide 1
    </li>
    <li slide>
         My Slide 2 
    </li>
    <li slide>
         My Slide 3
    </li>
</ul>

我可以动态地将其转换为图像滑块。以上工作正常,但如果标记看起来像这样:

<ul image-slider>
    <li slide ng-repeat="slide in data.slider.slides">
         My Slide {{$index}}
    </li>
</ul>

然后ng-repeatimage-slider指令运行之前没有完成,这意味着我无法访问所有幻灯片来实现我的魔力。

有没有办法告诉image-slider指令等待其中的任何指令在触发前完成?

我已经阅读了以下问题:

这些似乎都没有解决这个问题的答案,所以我想我会提出一个更简洁的问题,希望找到答案。

2 个答案:

答案 0 :(得分:7)

我建议采用一种更简单的方法。使用$timeout功能。如果将$timeout设置为零,它将在所有内容运行后完全运行:

app.directive("imageSlider", [ '$timeout', function($timeout) {
    return function(scope, element, attrs)
    {
        // your data is defined in scope.data.slider.slides

        $timeout(function() 
        {
            // This code will run whenever the page has finished processing
            // So it will run after ng-repeat has finished
        }, 0);
    }
}]);

答案 1 :(得分:5)

所以最简单的方法是在slide指令和image-slider指令之间使用directive to directive communication。这是你做的:

app.directive("imageSlider", [ '$log', function($log) {
    return {
        scope: {
        },
        controller: function($scope) {

            $scope.slides = [];

            // this is a normal controller method that is NOT exposed to other directives
            $scope.startGallery = function() {
            };

            // this method will be exposed to directives that require imageSlider
            this.addSlide = function(slide) {
                $scope.slides.push( slide );
            }
        }
    };
} ]);


app.directive('slide', [ '$log', function($log) {
    return {
        require: "^imageSlider",
        link: function($scope, elem, attribs, ctrls ) {
            ctrls.addSlide( $scope );
        }
    };
} ] );

这样,imageSlider可以提供幻灯片界面进行通信。请注意this.functionName与$ scope.functionName的区别。前者是将方法暴露给其他指令的一种方式。

相关问题