小编典典

ng-repeat完成后调用函数

angularjs

我试图实现的基本上是“重复完成渲染”处理程序。我能够检测到何时完成,但是我不知道如何从中触发功能。

检查小提琴:http :
//jsfiddle.net/paulocoelho/BsMqq/3/

JS

var module = angular.module('testApp', [])
    .directive('onFinishRender', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                element.ready(function () {
                    console.log("calling:"+attr.onFinishRender);
                    // CALL TEST HERE!
                });
            }
        }
    }
});

function myC($scope) {
    $scope.ta = [1, 2, 3, 4, 5, 6];
    function test() {
        console.log("test executed");
    }
}

的HTML

<div ng-app="testApp" ng-controller="myC">
    <p ng-repeat="t in ta" on-finish-render="test()">{{t}}</p>
</div>


:从finishmove的工作提琴:http
:
//jsfiddle.net/paulocoelho/BsMqq/4/


阅读 312

收藏
2020-07-04

共1个答案

小编典典

var module = angular.module('testApp', [])
    .directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit(attr.onFinishRender);
                });
            }
        }
    }
});

请注意,我没有使用.ready(),而是将其包装在中$timeout$timeout确保在ng重复元素真正完成渲染后$timeout执行(因为将会在当前摘要周期的末尾执行-
并且也会在$apply内部调用,与不同setTimeout)。因此,ng- repeat完成后,我们$emit将向外部范围(同级和父范围)发出事件。

然后在您的控制器中,可以使用以下命令进行捕获$on

$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
    //you also get the actual event object
    //do stuff, execute functions -- whatever...
});

使用html看起来像这样:

<div ng-repeat="item in items" on-finish-render="ngRepeatFinished">
    <div>{{item.name}}}<div>
</div>
2020-07-04