Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
178 views
in Technique[技术] by (71.8m points)

javascript - angular.js: model update doesn't trigger view update

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?

additionally my code:

service:

(function () {
    app.factory('Push', ['$rootScope', function ($rootScope) {
        socket.on('new-tweet', function (msg) {
            $rootScope.$broadcast('new-tweet', msg);
        });
    }]);
}());

controller:

(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);
            }
        });
    });
}());

the whole project is here: https://github.com/hochitom/node-twitter-client

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
        };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...