Angular 指令,其中需要两个属性之一
Angular directive where one of two attributes are required
如何编写需要 ng-model
或 k-ng-model
的指令?文档不包括这个:(
app.directive('myDir', function () {
return {
require: 'ngModel || kNgModel',
// omitted
};
});
您需要将它们作为字符串数组传入。
您无法告诉 Angular 至少其中一个需要可用,因此将它们设置为可选,如果两者之一可用,请检查 link 函数。将您的代码更新为:
app.directive('myDir', function () {
return {
require: ['?ngModel', '?kNgModel'],
link: function(scope, element, attrs, controllers){
if(!controllers[0] && !controllers[1]){
throw 'myDir expects either ng-model or k-ng-model to be defined';
}
}
};
});
如何编写需要 ng-model
或 k-ng-model
的指令?文档不包括这个:(
app.directive('myDir', function () {
return {
require: 'ngModel || kNgModel',
// omitted
};
});
您需要将它们作为字符串数组传入。
您无法告诉 Angular 至少其中一个需要可用,因此将它们设置为可选,如果两者之一可用,请检查 link 函数。将您的代码更新为:
app.directive('myDir', function () {
return {
require: ['?ngModel', '?kNgModel'],
link: function(scope, element, attrs, controllers){
if(!controllers[0] && !controllers[1]){
throw 'myDir expects either ng-model or k-ng-model to be defined';
}
}
};
});