我有一个全局变量,如果有新消息,该变量每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)
我该如何实现?
您可以尝试使用本机js事件,并参考侦听器的回调中的services / scopes / etc在您的angularjs控制器中添加一个侦听器。
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events在页面加载等事件中全局创建事件。 HasNewMessage状态更改时,在startInterval回调中调度它。
将监听器添加到您的指令控制器中,类似于手表。