Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
37
rated 0 times [  42] [ 5]  / answers: 1 / hits: 46015  / 12 Years ago, sat, june 30, 2012, 12:00:00

I'm just starting to familiarize with AngularJS, but I would like to build a web app that has a view that gets auto-upated in real-time (no refresh) for the user when something changes in the server-side database.



Can AngularJS handle this (mostly) automatically for me? And if so, what is the basic mechanism at work?



For example, do you somehow setup AngularJS to poll the DB regularly for model changes? Or use some sort of Comet-like mechanism to notify AngularJS client-side code that the model has changed?



In my application, the challenge is that other (non-web) server-side software will be updating the database at times. But this question applies equally to pure web-apps where you might have multiple clients changing the database through AngularJS web clients, and they each need to be updated when one of them makes a change to the DB (model).


More From » angularjs

 Answers
25

You have a few choices...




  1. You could do polling every X milliseconds using $timeout and $http, or if the data you're using is hooked up to a REST service, you could use $resource instead of $http.


  2. You could create a service that uses some Websocket implementation and uses scope.$apply to handle changes that are pushed by the socket.
    Here's an example using socket.io, a node.js websocket library:



    myApp.factory('Socket', function($rootScope) {
    var socket = io.connect('http://localhost:3000');

    //Override socket.on to $apply the changes to angular
    return {
    on: function(eventName, fn) {
    socket.on(eventName, function(data) {
    $rootScope.$apply(function() {
    fn(data);
    });
    });
    },
    emit: socket.emit
    };
    })

    function MyCtrl($scope, Socket) {
    Socket.on('content:changed', function(data) {
    $scope.data = data;
    });
    $scope.submitContent = function() {
    socket.emit('content:changed', $scope.data);
    };
    }

  3. You could get really high tech and create a websocket implementation which syncs an Angular model with the server. When the client changes something, that change gets automatically sent to the server. Or if the server changes, it gets sent to the client.

    Here's an example of that in an old version of Angular, again using socket.io: https://github.com/mhevery/angular-node-socketio




EDIT: For #3, I've been using Firebase to do this.


[#84555] Thursday, June 28, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dominics

Total Points: 424
Total Questions: 99
Total Answers: 107

Location: South Korea
Member since Fri, Sep 11, 2020
4 Years ago
dominics questions
Wed, Apr 6, 22, 00:00, 2 Years ago
Thu, Jan 13, 22, 00:00, 2 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
;