我有一个小问题,每次轮询器超时时我都无法更新视图中的Poller.msgdata。
所以我要做的是从服务接收Poller.msgdata和Poller.newdata TRUE或FALSE,然后在{{inbox}}内动态输出。但是$ scope.inbox是空的,因为在第一次检索时数据是未定义的,这不是问题。事实上,当Poller超时时,msgdata和newdata不会更新。
{{inbox}}每次都应为TRUE或FALSE并相应更新。 如果您需要更多详细信息,请告诉我们。
app.controller("taskbarController", ['$scope', 'authData', '$location', 'projectsModal', 'sendMessageModal', 'Poller',
function ($scope, authData, $location, projectsModal, sendMessageModal, Poller) {
$scope.inbox = Poller.msgdata;
$scope.project = Poller.newdata;
$scope.projects = Poller.projects;
$scope.messages = Poller.messages;
}]);
以下是更新msgdata和newdata的Poller:
app.factory('Poller', Poller);
Poller.$inject = ['$http', '$timeout'];
function Poller($http, $timeout) {
var projectcache = { response: [], calls: 0 };
var msgcache = { response: [], calls: 0 };
var newdata;
var msgdata;
var poller = function () {
$timeout(poller, 5000);
$http.get('http://localhost/app/controllers/php/getProjects.php')
.then(function(r) {
if (r.data.projects.length > projectcache.response.length) {
newdata = true;
projectcolor = 'green';
angular.copy(r.data.projects, projectcache.response);
} else {
newdata = false;
projectcolor = 'green';
};
});
$http.get('http://localhost/app/controllers/php/getMessages.php')
.then(function(m) {
if (m.data.messages.length > msgcache.response.length) {
msgdata = true;
msgcolor = 'green';
angular.copy(m.data.messages, msgcache.response);
} else {
msgdata = false;
msgcolor = 'green';
};
});
};
poller();
return {
projects: projectcache.response,
messages: msgcache.response,
newdata: newdata,
msgdata: msgdata
};
};
最后我在部分内部显示为:
{{inbox}}
答案 0 :(得分:0)
这里的例子。 $ scope。$ apply做什么:What does $scope.$apply() do?
app.controller("taskbarController", ['$scope', 'authData', '$location', 'projectsModal', 'sendMessageModal', 'Poller','$timeout','$interval',
function ($scope, authData, $location, projectsModal, sendMessageModal, Poller,$timeout,$interval) {
$scope.inbox = Poller.msgdata;
$scope.project = Poller.newdata;
$scope.projects = Poller.projects;
$scope.messages = Poller.messages;
$timeout(function ()
{
//Lets see if $scope.$apply does the magic and the data are set
$scope.$apply();
console.log($scope.inbox);
},5000);
//Call every second to see if the variable changes or not.
$interval(function ()
{
console.log("check inbox:" + $scope.inbox);
},1000);
}]);
如果这没有用,请尝试在$ scope中设置变量。$ apply function:https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply
app.controller("taskbarController", ['$scope', 'authData', '$location', 'projectsModal', 'sendMessageModal', 'Poller','$timeout','$interval',
function ($scope, authData, $location, projectsModal, sendMessageModal, Poller,$timeout,$interval) {
$scope.inbox = "";
$scope.project = "";
$scope.projects = "";
$scope.messages = "";
$scope.$apply(function ()
{
$scope.inbox = Poller.msgdata;
$scope.project = Poller.newdata;
$scope.projects = Poller.projects;
$scope.messages = Poller.messages;
});
}]);