In search of a 'sticky' directive that can trigger the addition of a css class to an element when it reaches the top of a page and also notify the changes in its state, I have declared a scope like { onStickyChange: '&' }
. My goal is to utilize this directive within an angularjs component as follows:
<my-component sticky on-sticky-change="$ctrl.onStickyChange(sticky)">
</my-component>
My expectation was for the directive to inform the parent controller about the stick/unstick events of my-component. However, instead I encounter the following error:
Error: [$compile:multidir] Multiple directives [myComponent, sticky] requesting new/isolated scopes on: http://errors.angularjs.org/1.6.2/$compile/multidir?p0=myComponent&p1=&p2=s…icky%3D%22%22%20on-sticky-change%3D%22%24ctrl.onStickyChange(sticky)%22%3E at angular.js:68 at assertNoDuplicate (angular.js:10049) at applyDirectivesToNode (angular.js:9237) at compileNodes (angular.js:8826) at compileNodes (angular.js:8838) at compileNodes (angular.js:8838) at compile (angular.js:8707) at angular.js:1847 at Scope.$eval (angular.js:18017) at Scope.$apply (angular.js:18117)
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;
}
}
}]);
Can anyone suggest a solution to this issue?
PS: For reference, here is a plunk.