angular - ng-if - how to callback after ng-if template has been rendered

前端 未结 4 1214
再見小時候
再見小時候 2021-02-18 18:47

in Angular, I need to call a function after an element with certain class has been loaded. Display of the element is controlled via ng-if=\'expr\'. Value of $scope.expr is set a

4条回答
  •  暖寄归人
    2021-02-18 19:20

    The directive could look something like this:

    import * as angular from 'angular';
    
    class OnFinishRenderDirective implements angular.IDirective {
    
      public restrict = 'A';
      public replace = false;
    
      public link = (
        scope: any,
        // scope:        angular.IScope,
        element: angular.IAugmentedJQuery,
        attr: any,
        modelCtrl: any,
        link: angular.ITemplateLinkingFunction ) => {
    
        if ( scope.$last === true ) {
          this.$timeout(() => {
            scope.$emit( 'elementRendered' );
          } );
        }
    
      }
    
      constructor( private $timeout: angular.ITimeoutService ) { }
    
    }
    
    export function onFinishRenderFactory(): angular.IDirectiveFactory {
    
      var directive = ( $timeout: angular.ITimeoutService ) => new OnFinishRenderDirective( $timeout );
      directive.$inject = [ '$timeout' ];
      return directive;
    }
    

    You would have to import it and add to your module

    import { onFinishRenderFactory } from './onFinishRender/onFinishRender.directive';
    
    angular.module( 'yourModule', [] )
    .directive( 'onFinishRender', onFinishRenderFactory() )
    

    Then you can use the directive somewhere in your markup to emit the event when the directive has been rendered.

    I am rendered

    You could even add an extra attribute in the directive DIV which you can then grab from the ATTR object in the link function and add to your $emit function to identify this specific DIV to be rendered.

    Does that answer your question?

提交回复
热议问题