2014-12-13 32 views
0

我需要對帶有指令的元素應用條件修改,然後將其放入新模板中。我不想'重寫'它。修改angularjs指令中的元素並將其重新注入模板中

我還沒有弄明白,謝謝btw!

我知道我可以使用translude,但我希望能夠有條件地修改模板。

HTML:

<directive-name></directive-name> 

JS:

.directive('directiveName', function($compile) { 
    return { 
    restrict: 'E', 
    link : { 
     pre: function(scope, iElement, iAttributes) { 
     if(condition) { 
      iElement.attr('a-attribute', "field") 
      break; 
     } 
     else { 
      iElement.attr('b-attribute', "field")      
      break; 
     } 
     var template = 
      '<pre>' + // Some very cool template here 
      iElement.html() + // Here it's where it doesn't work :(
      '</pre>'; 
     newElement = $compile(template)(scope); 
     iElement.replaceWith(newElement);  
     } 
    }, 
    } 
}) 

回答

0

嘗試是這樣的:

.directive('nsDirective', ['$compile', function($compile) { 
    return { 
     restrict: 'AE', 
     controller: 'nsDirectiveCtrl', 
     link: function(scope, element, attributes, controller) { 
      var build = function() { 
       var html = ''; 
       if (attributes.type === 'a') { 
        html = '<div ns-directive-a></div>'; 
       } 
       element.empty().append($compile(html)(scope)); 
      }; 
      // Init 
      build(); 
     } 
    }; 
}]) 
+0

感謝您的回答科裏,但我需要保留原始元素,以防他們的一些其他屬性添加到它。 – leseulsteve 2014-12-13 03:45:19

0

明白了!

我需要iElement [0] .outerHTML!

'<pre>' + // Some very cool template here 
    iElement[0].outerHTML 
'</pre>';