【发布时间】:2015-04-04 15:28:07
【问题描述】:
我使用 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 */
}
});
}
};
}])
但是 scope.$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?
【问题讨论】:
-
你为什么不给指令一个不同的名字?
-
因为如果我给不同的名字它不会覆盖 lib 指令。
标签: angularjs twitter-bootstrap angularjs-directive angularjs-scope