NG重复后运行指令

Run Directive After NG-Repeat

本文关键字:运行 指令 NG      更新时间:2023-09-26

因此,我希望尽可能将我的插件库转移到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指令在启动之前等待其中的任何指令完成?

我已经阅读了以下问题:

  • ng重复后运行的指令
  • Angularjs自定义指令在ng repeat运行后高亮显示文本
  • 在子指令之后运行父指令

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

我建议一种更简单的方法。使用$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);
    }
}]);

因此,最简单的方法是使用幻灯片指令和图像滑块指令之间的指令对指令通信。以下是您要做的:

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的区别。前者是向其他指令公开方法的一种方式。