问题描述
我需要一个'sticky'指令,该指令在页面顶部将css类添加到元素中,并发出其状态更改的信号.因此,我定义了一个{ onStickyChange: '&' }
之类的范围.现在,我想在angularjs组件中使用指令,例如:
I need a 'sticky' directive that adds a css class to element when it is at the top of a page and also signals the changes in its state. For that reason I define a scope like { onStickyChange: '&' }
. Now I'd like to use the directive in an angularjs component like:
<my-component sticky on-sticky-change="$ctrl.onStickyChange(sticky)">
</my-component>
我希望该指令在my-component粘贴/取消粘贴时通知父控制器.但是我收到以下错误:
I expected the directive to notify the parent controller when the my-component is sticked/unsticked. However I get the following error:
app.component('myComponent', {
template: '<div style="height: 6000px; width: 100%; background-color: #ccf></div>',
controller: function () {
this.is = 'nothing';
}
});
app.directive('sticky', ['$window', function($window) {
return {
restrict: 'A',
scope: { onStickyChange: '&' },
link: link
};
function link(scope, element, attributes) {
if (typeof scope.onStickyChange !== 'function' ) {
throw Error('Sticky requires change handler');
}
let sticky = isSticky(element);
angular.element($window).bind('scroll', _.throttle(onWindowScroll, 60));
function onWindowScroll() {
let isNowSticky = isSticky(element);
if (sticky === isNowSticky) {
return;
}
sticky = isNowSticky;
if (sticky) {
element.addClass('sticky');
}
else {
element.removeClass('sticky');
}
scope.onStickyChange({ sticky: sticky });
}
function isSticky(element) {
return window.scrollTop() > element.position().top;
}
}
}]);
如何解决该问题?
PS:有一个朋克.
推荐答案
发生错误是因为component指令和attribute指令都试图创建隔离作用域.
The error occurs because both the component directive and the attribute directive are trying to create an isolate scope.
从文档中:
对同一元素应用多个不兼容指令的示例场景包括:
Example scenarios of multiple incompatible directives applied to the same element include:
- 多个指令要求隔离范围.
— AngularJS错误参考-错误:$ compile:multidir
解决方案是重新编写attribute指令以在不创建隔离范围的情况下工作:
The solution is to re-write the attribute directive to work without creating an isolate scope:
app.directive('sticky', function($window, $parse) {
return {
restrict: 'A',
̶s̶c̶o̶p̶e̶:̶ ̶{̶ ̶o̶n̶S̶t̶i̶c̶k̶y̶C̶h̶a̶n̶g̶e̶:̶ ̶'̶&̶'̶ ̶}̶,̶
scope: false,
link: postLink
};
function postLink(scope, elem, attrs) {
//code ...
̶s̶c̶o̶p̶e̶.̶o̶n̶S̶t̶i̶c̶k̶y̶C̶h̶a̶n̶g̶e̶(̶{̶ ̶s̶t̶i̶c̶k̶y̶:̶ ̶s̶t̶i̶c̶k̶y̶ ̶}̶)̶;̶
$parse(attrs.onStickyChange)(scope, { sticky: sticky });
//code ...
}
});
使用 $ parse服务来评估on-sticky-change
属性.
这篇关于错误:[$ compile:multidir]带有属性指令的组件指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!