我使用了lib angular-bootstrap,并且我重叠了一个指令:
.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig',
function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) {
return {
restrict: 'EA',
require: 'ngModel',
scope: {
isOpen: '=?',
currentText: '@',
clearText: '@',
closeText: '@',
dateDisabled: '&'
},
link: function(scope, element, attrs, ngModel) {
/* Other code in lib */
scope.$watch('isOpen', function(value) {
if (value) {
console.log("watch lib dir");
scope.$broadcast('datepicker.focus');
scope.position = appendToBody ? $position.offset(element) : $position.position(element);
scope.position.top = scope.position.top + element.prop('offsetHeight') + 50;
$document.bind('click', documentClickBind);
} else {
$document.unbind('click', documentClickBind);
}
});
/* Other code in lib */
}
};
}])
我创建自定义指令,而不是使用require指令(因为在html布局中我使用此指令作为属性而在另一个属性旁边我不能,因为它不属于第一个属性的范围),但只是用相同的签名写的:
.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig',
function ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) {
return {
restrict: 'EA',
priority: 1,
link: function(scope, element, attrs, ngModel) {
scope.$watch('isOpened', function(value) {
if(value){
/*custom code */
}
});
}
};
}])
但是范围。$ watch没有看到' isOpened' (因此无法正常工作),我在定义中添加了自定义指令:
scope: {
isOpen: '=?'
}
在控制台抓住抛出异常之后:
Error: [$compile:multidir] Multiple directives [datepickerPopup, datepickerPopup] asking for new/isolated scope on: <input type="text" name="callDate" class="form-control ng-pristine ng-untouched ng-valid" ng-model="callDate" datepicker-popup="MM/dd/yyyy" datepicker-positioning="" is-open="opened" ng-required="true">
如何重叠lib指令而不使用require?
答案 0 :(得分:0)
是的,因为您无法在Angular中重新定义指令。您需要使用装饰器来扩展/替换它们。
app.config(function ($provide) {
$provide.decorator('datepickerPopupDirective', ['$delegate', '$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig', function($delegate, $compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) {
return {
restrict: 'EA',
priority: 1,
scope: {
isOpen: '=?'
},
link: function(scope, element, attrs) {
scope.$watch('isOpen', function(value) {
if(value){
/*custom code */
}
});
}
};
}]);
});
如果您不打算扩展原始指令,则可以省略$delegate
依赖性。