Execution events after rendering of angular ng repeat

When using angular ng repeat, sometimes you need to execute js script after ng repeat is executed
angular doesn't use the events rendered by ng repeat, but it can be implemented through directive

Suppose we need to set the length and width of the picture to be equal through js script after ng repeat is executed

Using the jquery selector $("img") or document.getElementsByTagName("img") directly can not get the required dom elements, because the ng repeat is not finished when performing these operations, and the dom we need does not exist

Code it

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>

    <style type="text/css">
        .container{
            width:200px;
        }

        img{
            width:50%;
        }
    </style>
</head>
<body ng-app="myApp">
    <div ng-controller="myController" class="container">
        <ul>
            <li ng-repeat="src in srcs" class="repeat-finish">
                <img ng-src="{{src}}">
            </li>
        </ul>
    </div>
</body>

<script type="text/javascript">
    var myApp = angular.module('myApp', []);

    myApp.controller("myController", function($scope){
        $scope.srcs = ["../../img/clz_1.jpeg", "../../img/clz_5.jpeg", "../../img/clz_3.jpg"];
    });

    myApp.directive("repeatFinish", function(){
        return{
            //C for class indicates that the instruction is called by class name, and the hump name repeat finish repeatfinish is needed
            restrict:"C", 
            link:function(scope, element, attr){
                if(scope.$last == true){
                    //Here is the event after ng repeat rendering

                    console.log("n-repeat Finished rendering!");

                    //Here is an example. When using angular, you should try to avoid directly operating dom
                    var imgs = document.getElementsByTagName("img");
                    for(var i = 0; i < imgs.length; i++){
                        imgs[i].height = imgs[i].width;
                    }
                }
            }
        }
    });
</script>
</html>

Tags: angular Javascript JQuery

Posted on Sun, 03 May 2020 22:16:03 -0400 by bluesoul