指令的内容在编译阶段被删除,因为你的指令有transclude: true
(我假设是这样,因为你正在使用ng-transclude
)。
在这种情况下,内容可以通过传入的transclude
函数获得(这实际上是ng-transclude
在幕后使用的)。
transclude
函数是link
(或预链接)函数的第 5 个参数:
link: function(scope, element, attrs, ctrls, transclude){
var transcludedContents; // jqLite of the contents
transclude(function(clone){
transcludedContents = clone;
});
// do whatever you do to extract ng-message values from transcludedContents
// just remember, that it could also come in the form:
// <ng-message when="required"> and
// <div ng-message-exp="errorMessage.type">
}
可能我们中间比较懒惰的人不想处理 DOM 计数,因此您可以为ng-message
指令创建另一个处理程序,该处理程序与您交互my-directive
以注册自身:
.directive("myDirective", function() {
return {
transclude: true,
templateUrl: "myDirective.template.html",
controller: function() {
var messages = [];
this.registerNgMessage = function(val) {
messages.push(val);
};
}
};
})
.directive("ngMessage", complementaryNgMessageDirective)
.directive("ngMessageExp", complementaryNgMessageDirective);
function complementaryNgMessageDirective() {
return {
priority: 10, // must be higher than ngMessage, because ngMessage is terminal
require: "^?myDirective", // must be optional not to break existing code
link: function(scope, element, attrs, myDirectiveCtrl) {
if (!myDirectiveCtrl) return; // do nothing, if not paired with myDirective
var staticExp = attrs.ngMessage || attrs.when;
var dynamicExp = attrs.ngMessageExp || attrs.whenExp;
var val;
if (dynamicExp) {
val = scope.$eval(dynamicExp);
} else {
val = staticExp;
}
myDirectiveCtrl.registerNgMessage(val);
}
};
}