Showing posts with label ng-repeat. Show all posts
Showing posts with label ng-repeat. Show all posts

Thursday, December 1, 2016

Angularjs: Calling a function when ng-repeat has finished


<!DOCTYPE html>
<html>
<head>
    <title>Angularjs: Calling a function when ng-repeat has finished</title>
    <style type="text/css">
        div.log {
            border: 2px solid gray;
            color: black;
            padding: 10px;
            font-size: 20px;
            font-family: monospace;
        }
        div.log div {
            padding: 10px;
        }
    </style>

    <script src="http://code.angularjs.org/1.2.12/angular.js"></script>
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>

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

        app.controller("MyController", function($scope) {
            $scope.items = [];
            $scope.items.push({"name": "Pritom"});
            $scope.items.push({"name": "Kumar"});

            var log = $(".log");
            $scope.log = function(e) {
                log.prepend("<div>" + e + "</div>");
            }
        })

        app.directive("myCustomValidation", function($timeout) {
            return {
                restrict: "A",
                require: "ngModel",
                link: function(scope, elem, attrs, ctrl) {
                    /**
                     * If you dont use $timeout then nothing found.
                     * You can try yourself.
                     */
                    $timeout(function () {
                        scope.$apply(function () {
                            scope.log(elem.val())
                        })
                    })
                }
            }
        })
    </script>
</head>

<body>
<div data-ng-app="myApp" data-ng-controller="MyController">
    <div>
        <div ng-form="myForm" data-ng-repeat="item in items">
            <div style="border:1px solid blue;padding:10px;">
                <input type="text" name="name" ng-model="item.name" ng-maxlength="10"
                       my-custom-validation required style="width:100%;"/>
            </div>
        </div>
        <div class="log"></div>
    </div>
</div>
</body>
</html>

Result using $timeout:


Result without using $timeout: