2014-02-16 28 views
3

以下指令:防止從複製的角度屬性時更換=真

var app = angular.module('demo', []); 
app.directive('myDirective', function() { 
    return { 
     restrict: 'E', 
     template: '<h1>Foo bar</h1>' 
    }; 
}); 

用下面的用法:

<my:directive foo="bar"></my:directive> 

呈現以下HTML:

<my:directive foo="bar"><h1>Foo bar</h1></my:directive> 

因爲我想用我提供的模板replace:true替換我的指令。這將產生以下HTML:

<h1 foo="bar">Foo bar</h1> 

注意,角複製了我的指令的屬性模板要素(foo="bar")。我怎樣才能防止這種行爲?

回答

2

您可以手動刪除屬性的指令的鏈接功能:

.directive('myDirective', function() { 
     return { 
      restrict: 'E', 
      replace: true, 
      template: '<h1>Foo bar</h1>', 
      link: function(scope, elm, attrs){ 
       elm.removeAttr('foo'); 
      } 
     }; 
    }); 

這裏的a fiddle這個指令在您的情況的工作。

編輯:您可以擴展此刪除所有與一個簡單的循環動態屬性:

.directive('myDirective', function() { 
     return { 
      restrict: 'E', 
      replace: true, 
      template: '<h1>Foo bar</h1>', 
      link: function(scope, elm, attrs){ 
       for(var attr in attrs.$attr){ 
        elm.removeAttr(attr); 
       } 
      } 
     }; 
    }); 
+0

這並不是刪除屬性的動態方法,有一次刪除指令的所有屬性的通用方式他們已經精心製作了? –

+0

我明白你的問題,但對downvote感到失望。我的答案適用於所問的問題,擴展它以刪除所有屬性非常簡單。請參閱編輯。 – jbll

+0

謝謝。發佈一個在大多數情況下工作正常的答案總是更好:) –