How to conditionally apply a template via custom Angular directives?

后端 未结 6 833
攒了一身酷
攒了一身酷 2020-12-29 02:37

DEMO

Consider the following directive:

angular.module(\'MyApp\').directive(\'maybeLink\', function() {
  return {
    replace: true,
    s         


        
6条回答
  •  忘掉有多难
    2020-12-29 02:50

    The following is a solution that provides dynamic updates. Usage:

    etc.

    app.directive('rewriteAsSpan', function($compile){
      return {
        restrict: 'A',
        template: '',
        replace: true,
    
        // we transclude the element because when it gets replaced with the span
        // we want all the properties from the original element
        transclude: 'element',
    
        compile: function(tElement, tAttrs){
    
          return {
            post: function(scope, element, attrs, controller, transclude){
              var rewrittenEl, originalEl;
    
              transclude(scope, function(clone){
                originalEl = clone;
              });
    
    
              scope.$watch(attrs.rewriteAsSpan, function(value){
                if (value === undefined || value === true){
                  if (!rewrittenEl){
                    // lazy compile and cache the rewritten element
                    transclude(scope, function(clone){
                      rewrittenEl = tElement;
                      rewrittenEl.html(clone.html());
                      // remove this directive because the $compile would get infinite
                      rewrittenEl.removeAttr('rewrite-as-span');
                      $compile(rewrittenEl)(scope);
                    });
    
                  }
    
                  element.replaceWith(rewrittenEl);
                  element = rewrittenEl;
    
                } else {
                  element.replaceWith(originalEl);
                  element = originalEl;
                }
              });
    
            }
          };
        }
      };
    });
    

    Code and specs as a gist

提交回复
热议问题