TurboLinks with Angular

不问归期 提交于 2019-12-08 18:34:30
Ryan

After a lot of trial and error, this does the job, but is not exactly what I'm looking for. Would like to hear if anyone else has any suggestions. It would be ideal if this could happen automatically without a service having to remember to cancel it's own intervals. Also accessing $rootScope in this manner just feels so dirty...

// Broadcast Event when TurboLinks is leaving
document.addEventListener('turbolinks:before-visit', function(event) {
    console.log('TurboLinks Leaving', event);
    var $body = angular.element(document.body);
    var $rootScope = $body.injector().get('$rootScope');
    $rootScope.$apply(function () {
        $rootScope.$broadcast('page.leaving');
    });
});

I'm then injecting $rootScope into my service as well as keeping a reference to the interval. Once it hears the page.leaving event, it cancels the interval:

var self = this;
self.interval = $interval(myFunction, intervalPoll);

....

$rootScope.$on('page.leaving', function() {
    $interval.cancel(self.interval);
});

So this gets the job done... but would love to find a better way. Credit for accessing $rootScope this way came from here: How to access/update $rootScope from outside Angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!