问题描述
我目前正在开发基于 Web 的 twitter 客户端,因此我使用了 angular.js、node.js 和 socket.io.我通过 socket.io 将新推文推送到我的客户端,在那里服务等待新推文.当一条新推文到达时,该服务通过 $broadcast 发送一个事件.
i'm currently working on a web based twitter client and therefore i used angular.js, node.js and socket.io. i push new tweets via socket.io to my client, where a service waits for new tweets. when a new tweet arrives, the service send an event via $broadcast.
在我的控制器中是一个事件监听器,传入的推文在一个单独的函数中被处理.此函数只是将新推文推送到我的推文范围内.
in my controller is a event listener, where incoming tweets are being processed in an seperate function. this function simply pushes the new tweet in my tweet scope.
现在,我的问题是,我的视图没有更新,但我可以看到我的范围在扩大.也许你们中的一个人有一个想法,我该如何解决这个问题?
now, my problem ist, that my view is not updating but i can see my scope growing. maybe one of you have an idea, how i can solve this?
另外我的代码:
服务:
(function () {
app.factory('Push', ['$rootScope', function ($rootScope) {
socket.on('new-tweet', function (msg) {
$rootScope.$broadcast('new-tweet', msg);
});
}]);
}());
控制器:
(function () {
app.controller("StreamCtrl", function StreamCtrl ($scope, $rootScope, $http, Push) {
$scope.tweets = [];
$http
.get('/stream')
.then(function (res) {
$scope.tweets = res.data;
});
$scope.addTweet = function (data) {
$scope.tweets.push(data);
console.log($scope.tweets);
};
$rootScope.$on('new-tweet', function (event, data) {
if (!data.friends) {
$scope.addTweet(data);
}
});
});
}());
整个项目在这里:https://github.com/hochitom/node-twitter-client
推荐答案
在addTweet中添加下面这行代码,问题就解决了
Adding below line of code in addTweet and the problem would be solved
$scope.addTweet = function (data) {
$scope.tweets.push(data);
$scope.$apply();
console.log($scope.tweets);
};
这篇关于angular.js:模型更新不会触发视图更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!