如何在dom完成Angularjs中的渲染后运行指令

How to run a directive after the dom finished rendering in Angularjs

本文关键字:运行 指令 dom 完成 Angularjs      更新时间:2023-09-26

我正在尝试动态渲染模板,如何在{{tag}}渲染完成后运行指令?

指令:

angular.module('services', [])
    .directive('demo', function() {
        return {
            templateUrl: '/template.html',
            restrict: 'C'
        }
    });

控制器:

angular.module('controller', [])
    .controller('DemoCtrl', ['$scope', function($scope) {
        $scope.tag = "demo";
        $scope.clickHandler = function() {
            // do something when click button
        }
    }]);

视图:

<button ng-click="clickHandler()">Button</button>
<div class="{{tag}}"></div>

您可以在directive中使用以下结构:

 app.directive('example', function() {
    var directive : {
        link:link,
        restrict:'C',
        templateUrl:'...'
    } 
    function link($scope,$element,$attrs, $rootScope){
      angular.element(document).ready(function() {
         // dom here
      })
    }
    return directive;
}

试试看它是否对你有用。

正如@Cosmo所写,它需要在链接函数中完成,但只能等待整个文档,而只能等待指令dom就绪。链接函数的第二个参数是$element您可以使用它。

app.directive('example', function() {
var directive : {
    link:link,
    restrict:'C',
    templateUrl:'...'
} 
function link($scope, $element, $attrs, $rootScope){
  $element.ready(function() {
     // dom here
  })
}
return directive;
}