How to re-render a template in an AngularJS directive?

后端 未结 6 1180
一个人的身影
一个人的身影 2020-12-08 03:22

I\'ve create a directive that generates Twitter buttons. Since the scope variables on those buttons may change, I need to rebuild the button when it happens. Currently, I\'m

6条回答
  •  半阙折子戏
    2020-12-08 03:35

    Small variation on @rob answer:

    import * as angular from 'angular';
    
    class ReRenderDirective implements angular.IDirective {
    
      public restrict = 'A';
      public replace = false;
      public transclude = true;
      constructor( private $rootScope: angular.IRootScopeService, private $compile: angular.ICompileService ) {
    
      }
    
      public link = (
        scope: angular.IScope,
        element: angular.IAugmentedJQuery,
        attr: any,
        modelCtrl: any,
        transclude: angular.ITranscludeFunction ) => {
    
        let previousContent = null;
    
        let triggerRelink = () => {
          if ( previousContent ) {
            previousContent.remove();
            previousContent = null;
          }
    
          transclude(( clone ) => {
            element.append( clone );
            previousContent = clone;
    
            element.html( attr.compile );
            this.$compile( element.contents() )( scope );
          } );
    
        };
    
        triggerRelink();
        this.$rootScope.$on( attr.reRender, triggerRelink );
    
      }
    
    }
    
    export function reRenderFactory(): angular.IDirectiveFactory {
    
      var directive = ( $rootScope: angular.IRootScopeService, $compile: angular.ICompileService ) => new ReRenderDirective( $rootScope, $compile );
      directive.$inject = [ '$rootScope', '$compile' ];
      return directive;
    }
    

    Use this with:

    and combine it with a $broadcast somewhere in your code:

    this.$rootScope.$broadcast( 'responsive' );
    

    What I did, is listen to page resize, which will then trigger the broadcast. Based on this I am able to change the template of a component from desktop to mobile. Because the header-component in the example is transcluded, it get's rerendered and recompiled.

    This works like a charm for me.

    Thanks Rob for getting me on the right track.

提交回复
热议问题