AngularJS从全局变量更新范围的值

问题描述 投票:0回答:1

我有一个全局变量,如果有新消息,该变量每3分钟用于从服务器获取信息。变量名称为HasNewMessage。现在,我要做的就是在我的AngularJS应用之一中获取该变量的值。

我的指令是这个

commonApp.directive('osMessageList', ['getMessages', '$location', '$anchorScroll', 'searchMessages', 'userfactory', '_', '$rootScope', '$window',
function (getMessages, $location, $anchorScroll, searchMessages, userfactory, _, $rootScope, $window) {
return {
    restrict: 'A',
    scope: {
        messages: "="
    },
    controller: function ($scope) {
        $scope.hasNewMessages = false;
        $scope.$watch(function () {
            return $scope.hasNewMessages;
        }, function (newValue, oldValue) {
            if (newValue) {
            }
        }, true);
    },

function startInterval() {

// do something
// get scope of that directive and update the value

},SOME_TIME)

我该如何实现?

angularjs angularjs-directive
1个回答
0
投票
outside angularjs空间(即全局),则有点棘手。我认为有一个原因,您不能简单地使用$ interval服务并将其全部保留在angularjs框架中。

您可以尝试使用本机js事件,并参考侦听器的回调中的services / scopes / etc在您的angularjs控制器中添加一个侦听器。

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

在页面加载等事件中全局创建事件。 HasNewMessage状态更改时,在startInterval回调中调度它。

将监听器添加到您的指令控制器中,类似于手表。

© www.soinside.com 2019 - 2024. All rights reserved.