6
如何創建一個將其他指令添加到元素的指令?指令,將其他指令添加到angular.js中的相同元素
例如,我想:
<input ng-pattern='/[\\w\\d]+/' ng-maxlength='10'/>
如何創建一個將其他指令添加到元素的指令?指令,將其他指令添加到angular.js中的相同元素
例如,我想:
<input ng-pattern='/[\\w\\d]+/' ng-maxlength='10'/>
我想出了,似乎工作的解決方案:
.directive('tag', ['$compile', function($compile) {
return {
priority: 1000,
terminal: true,
compile: function(telement, attrs) {
attrs.$set('tag', null);
attrs.$set('ngMaxlength', '10');
attrs.$set('ngPattern', '/[\\w\\d]+/');
var link = $compile(telement);
return function($scope, $element) {
link($scope, function(clonedElement) {
$element.replaceWith(clonedElement);
});
}
}
}
}]);
的關鍵是
<input tag/>
爲被鏈接確保該指令比元素上的所有其他指令具有更高的優先級並終止,以便其他目錄ectives不被編譯和鏈接。
我不認爲$compile()
,鏈接功能,或terminal
是必要的。 Angular會自動爲我們編譯telement
。
.directive('tag', [function() {
return {
priority: 1000,
compile: function(telement, attrs) {
attrs.$set('tag', null);
attrs.$set('ngMaxlength', '10');
attrs.$set('ngPattern', '/[\\w\\d]+/');
}
};
}]);
測試這個HTML:
<input ng-model="test" ng-init="test=2" tag>
{{test}}
感謝您指出attrs。$設置給我!但是,似乎並沒有用這個來設置ng模型。任何想法爲什麼不呢?對你的plunker的修改顯示:http://plnkr.co/edit/ad2zIbNqW800KZi2Ulxn?p=preview – MrException 2013-07-12 21:02:52
@MrException,我不知道爲什麼它不起作用。這裏有一個關於這個問題的問題:http://stackoverflow.com/questions/17405790/adding-ngmodel-to-input-with-a-directive – 2013-07-14 02:16:51
超級@馬克,我一直拉着我的頭髮嘗試'attrs。 $ set('ng-pattern')'並不理解爲什麼它在html中看起來完全相同,但沒有任何事情發生。我想要說明的是,在我對當前的Firefox和Chrome以及Angular 1.0.7進行的快速測試中,至少「優先級:1000」對於模式ng驗證工作似乎並不需要。 – Daryn 2013-12-09 20:30:21