$scope.$apply doesn't do anything in a Chrome extension popup

旧街凉风 提交于 2019-12-14 02:53:37

问题


I'm writing a chrome extension that consists of a background process and a popup. The background process continually makes ajax requests to get new data, and the popup displays the info.

In an extremely simplified way, the background.js process looks like this:

var Background = {
    data: {},
    poll: function() {
        $.ajax({
            url: 'some_url',
            success: function(data) {
                this.data = data;
                chrome.extension.sendMessage('update');
            }.bind(this)
        });
    },
    startPolling: function() {
        setInterval(this.poll.bind(this), 10000);
    }
};
$(Background.startPolling.bind(Background));

This shoots of an ajax request every 10 seconds, gets some data back, and sets it to Background.data. Again, this is very simplified. You can see the sendMessage call in the success callback.

My popup.js looks something like this, also extremely simplified:

var Background = chrome.extension.getBackgroundPage().Background;

angular.module('App', [])
    .controller('PopupCtrl', function PopupCtrl($scope) {

        $scope.data = Background.data;

        chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
            if (request == 'update') {
                console.log('update');
                $scope.$apply();
            }
        });

    });

And of course, popup.html looks something like:

<html ng-app="App" ng-csp>
    <body ng-controller="PopupCtrl">
        <p>{{data.title}}</p>
        <p>{{data.body}}</p>
        <p>{{data.date}}</p>
    </body>
</html>

The message is definitely received, because I can see "update" print to the console every 10 second interval. I also know that the data is being updated properly because if I close and reopen the popup, the new data is displayed correctly. So $scope.$apply() is simply not doing anything.

How can I fix this?

来源:https://stackoverflow.com/questions/15595972/scope-apply-doesnt-do-anything-in-a-chrome-extension-popup

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