小心无限循环和重新编译,这里有一个更好的解决方案:Add directives from directive in AngularJS
angular.module('app')
.directive('commonThings', function ($compile) {
return {
restrict: 'A',
terminal: true, //this setting is important to stop loop
priority: 1000, //this setting is important to make sure it executes before other directives
compile: function compile(element, attrs) {
element.attr('tooltip', '{{dt()}}');
element.attr('tooltip-placement', 'bottom');
element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html
return {
pre: function preLink(scope, iElement, iAttrs, controller) { },
post: function postLink(scope, iElement, iAttrs, controller) {
$compile(iElement)(scope);
}
};
}
};
});
工作 plunker 可在以下网址获得:http ://plnkr.co/edit/Q13bUt?p=preview