AngularJS 从全局变量更新作用域值
AngularJS update value of scope from global variable
我有一个全局变量,用于在有新消息时每 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)
我怎样才能做到这一点?
如果 startInterval 函数在 之外 angularjs space(即全局),则有点棘手。我认为您不能简单地使用 $interval 服务并将其全部保存在 angularjs 框架中是有原因的。
您可以尝试使用原生 js 事件,并在您的 angularjs 控制器中添加一个监听器,并参考监听器回调中的 services/scopes/etc。
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
在页面加载或其他情况下全局创建事件。当 HasNewMessage 状态改变时,在您的 startInterval 回调中调度它。
在指令控制器中添加侦听器,类似于手表。
我有一个全局变量,用于在有新消息时每 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)
我怎样才能做到这一点?
如果 startInterval 函数在 之外 angularjs space(即全局),则有点棘手。我认为您不能简单地使用 $interval 服务并将其全部保存在 angularjs 框架中是有原因的。
您可以尝试使用原生 js 事件,并在您的 angularjs 控制器中添加一个监听器,并参考监听器回调中的 services/scopes/etc。
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events
在页面加载或其他情况下全局创建事件。当 HasNewMessage 状态改变时,在您的 startInterval 回调中调度它。
在指令控制器中添加侦听器,类似于手表。