如果您只需要确保该属性不是可选的并且它引用范围上的有效变量,那么请考虑(再次 - 如果您驳回该想法)将这些属性与隔离范围的 = 一起使用。
所以你可以指定所需的范围变量:
scope: { requiredVar: '=requiredAttribute' },
scopeRequired: [ 'requiredVar' ],
link 是修改行为的好地方,因为它涉及范围,并且(如果它嵌套在 compile 中)它可以从中获取对 this.scopeRequired 的引用。
当然,您可以在每个指令的基础上执行此操作,但如果您希望它作为全局行为...这是我用来分解指令的配方。
app.config(['$injector', function ($injector) {
var _get = $injector.get;
$injector.get = function patchedGet() {
var provider = _get.apply(this, arguments);
var providerName = 参数[0];
var directiveName = (providerName.match(/(.+)DirectiveProvider$/) || [])[1];
如果(指令名称){
var _$get = 提供者.$get;
console.log(['hi from injector get', arguments[0], provider.$get]);
provider.$get = 功能补丁$Get() {
var 实例 = _$get.apply(this, arguments);
console.log(['hi from provider $get', providerName, instances]);
angular.forEach(实例,函数(实例){
函数 getPatchedPostlink (postlink) {
返回函数 patchedPostlink(scope, element, attrs, ctrls) {
var _postlink = 后链接;
console.log(['hi from directive link', directiveName, scope, element, attrs, ctrls]);
// 这里是
if (scope.$$isolateBindings && instance.scopeRequired) {
var bindings = scope.$$isolateBindings;
angular.forEach(instance.scopeRequired, function (scopeVar) {
if (!bindings[scopeVar] || !attrs.hasOwnProperty(bindings[scopeVar].attrName)) {
throw new Error("作用域变量 '" + scopeVar + "', 指令 '" + directiveName + "' 需要,没有赋值!");
}
});
}
返回 angular.isFunction(_postlink) ? _postlink.apply(this, arguments) : undefined;
};
}
var _compile = instance.compile;
// 如果有 'compile' 则 'link' 无效
如果(_编译){
instance.compile = function patchedCompile(element, attrs) {
var compile = _compile.apply(实例,参数);
console.log(['hi from directive compile', directiveName, this, element, attrs]);
如果(!编译){
编译 = {};
} else if (angular.isFunction(compile)) {
编译 = { 帖子:编译 };
}
// compile.pre = getPatchedPrelink(compile.pre);
compile.post = getPatchedPostlink(compile.post);
返回编译;
};
} 别的 {
instance.link = getPatchedPostlink(instance.link);
}
}, 这个);
返回实例;
};
}
退货提供商;
};
}]);