利用angular指令监听ng-repeat渲染完成后执行脚本

利用angular指令监听ng-repeat渲染完成后执行脚本

转载自:https://www.cnblogs.com/mgqworks/p/7691580.html
业务中有时需要在异步获取数据并用ng-repeat遍历渲染完页面后执行某个操作,angular本身并没有提供监听ng-repeat渲染完成的指令,所以需要自己动手写。有经验的同学都应该知道,在ng-repeat模板实例内部会暴露出一些特殊属性index/first/middle/last/odd/even,index会随着每次遍历(从0开始)递增,当遍历到最后一个时,last的值为true,so,通过判断last的值来监听ng−repeat的执行状态,怎么在遍历过程中拿到last的值:自定义指令

AngularJs中,如何在ng-repeat完成之后,执行Js脚本

//ng-repeat生成4个li,生成后再执行自定义方法fn在每个li后加一根横线

    <script>
    var myapp=angular.module('myapp',[]);
    myapp.directive('onFinishRenderFilters', function ($timeout) {
        return {
            restrict: 'A',
            link: function(scope, element, attr) {
                if (scope.$last === true) {
                    $timeout(function() {
                        scope.$emit('ngRepeatFinished');//注册一个事件
                    });
                }

            }
        };
    }).controller('test',function($scope){
        $scope.fn=function(){
            $('.item').append('<hr/>')
        }
        $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {//监听事件
            //下面是在li render完成后执行的js
            $scope.fn()<br>       })<br>      })
</script>

<body ng-app="myapp" ng-controller="test">
<ul class="list" ng-init="aa=[1,2,3,4]">
  <li class="item" ng-repeat="x in aa" on-finish-render-filters> //在需要监控的地方,加上该directive
    hello world!
  </li>
  <ul>
</body>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值