如何编写一个angularjs指令,以增加渲染该元素的延迟?

时间:2019-01-24 04:13:24

标签: angularjs

如何编写一个angularjs指令,该指令会增加渲染该元素的延迟?

<div my-directive>
     Hello - show after 1 second.
</div>

angular.module('myapp').directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {

        }
    }
})

3 个答案:

答案 0 :(得分:0)

好吧,尽管您可以手动显示或隐藏元素,但我认为无法直接访问渲染过程

angular.module('myapp').directive('myDirective', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
          element.hide();            // hide on load
          $timeout(function() {
             element.show();         // show after delay
          }, 1000)
        }
    }
})

答案 1 :(得分:0)

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
    <script  >
    angular.module('myapp',[]);
        angular.module('myapp').directive('myDirective', function () {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    element.css("display", "none");
                    setTimeout(function(){ element.css("display", "block"); }, 1000);
                }
            }
        })
    </script>

</head>

<body ng-app="myapp">
    Start
    <div my-directive>
        Hello - show after 1 second.
    </div>

    <script src="" async defer></script>
</body>

</html>

答案 2 :(得分:0)

您可以使用范围变量和元素超时来延迟元素的渲染 ng-if位于指令的子元素中。

希望这会有所帮助。

var app = angular.module("myapp", []); 
app.directive('myDirective',  function( $timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
         $timeout(function() {
            scope.show = true;
         }, 1000);
        }
    }
});

app.controller("myCtrl", function($scope) {
    $scope.show = false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>


<div ng-app="myapp" ng-controller="myCtrl">
  <div my-directive>
   <div ng-if="show">
     Hello - show after 1 second.
    </div>
</div>
</div>