alonisser
alonisser

Reputation: 12078

Angular directive works on an element in the first page but stop working after navigation (probably a scope issue)

the directive code

directive('stFloatBar', function($log,$window){
        return{
            restrict:'A',
            replace:true,
            transclude:true,
            templateUrl:'partials/directives/topfloatnav.html',
//            scope: {target:'=stFloatBar'},
            link:function(scope,element,attrs){
                var oldvalue;
                $window = angular.element($window);

                        $window.on('scroll',function(ev){
                            scrollShow(attrs.stFloatBar);
                        });

               var back = element.find('.scrollBack');

                var scrollBack = function(){
                  scope.$apply($window[0].scrollTo(0));
                };

                back.bind('click',scrollBack);
                scope.shower = false;
                var scrollShow = function(dest){
                    var trigger =$(dest)[0].getBoundingClientRect().bottom;
                    var triggerPoint = attrs.stFloatTriggerpoint;

                    if (trigger < triggerPoint && scope.shower==false){
                        scope.shower = true;
                        scope.$apply(attrs.stSetfloat);
                    }
                    if(trigger > triggerPoint && scope.shower==true){
                        scope.shower=false
                        scope.$apply(attrs.stSetfloat);
                    }
                };
        }
        };
    })

and the html calling the directive:

<div st-float-bar="div.userTop" st-float-triggerpoint="80" st-setfloat="setShowFloat()" ng-show="showFloat"></div>

basically the directives need to calculate some data from the Html target element (Its bottom)

this work on the first page showing and hiding the floating bar correctly and listening to the scrolling event(doesn't matter if I start with page1 or page2) But when I navigate to the second page I get a console error:

Uncaught TypeError: Cannot call method 'getBoundingClientRect' of undefined

So I guess the problem is that the binding doesn't change, But I can figure how?

Thanks for the help!

Upvotes: 0

Views: 1018

Answers (1)

musically_ut
musically_ut

Reputation: 34288

In angular, the template is not rendered in the same $digest loop which runs the link function. Hence, the template of the element is empty on page change while the window's scroll event fires irrespective.

Solution is to check whether $(dest) found any elements at all and if it didn't, then not to take any action at all.

Sidenote: It is always best if a directive cleans up after itself by unregistering all event listeners when $destroy event is called on the $scope. Otherwise, the application runs a risk of running into a memory leak.

Upvotes: 2

Related Questions