Skip to content Skip to sidebar Skip to footer

How To Implement Automatic View Update As Soon As There Is Change In Database In Angularjs?

I am using AngularJs with Grails framework and using Mysql as Database. I want to implement feature like automatic view update as occur on Facebook. Till now i am able to send JSON

Solution 1:

For 'automatic' update of the views, I've used Grails Events Push Plugin, I suggest that you look at it. http://grails.org/plugin/events-push

It's really easy to send the events to the browser and in the client listen to them and update the AngularJS scope with the propper information.

Example

An angularJS file

window.grailsEvents = new grails.Events('http://myAppUrl.com', {enableXDR:true,readResponsesHeaders:false});

/**
 * Module for listening to grails events
 */
angular.module('grailsEvents', []).factory('grailsEvents', function() {
    returnwindow.grailsEvents
});

window.myModule = angular.module('myModule',['grailsEvents'])
   .run(function(){
       grailsEvents.on('myEvent',function(data){
          //Every time an event occurs, this will be executedconsole.log(data);
       });
   });

MyEvents.groovy (in grails-app/conf)

events = {
    'myEvent' browser:true
}

TestController.groovy (an example of a controller that sends an event)

classTestController{
    def index(){
       event(topic:'myEvent',data:MyDomain.list())
    }
}

Solution 2:

If you do have to use MySQL, I would suggest a slightly longer route keeping performance in mind. You definitely do not want to keep polling every X seconds. The SocketIO method indicated in the comments is a good way to go. However you need to expand your design a bit.

You will need to implement a "Topic" concept. For example, lets say you have a page called Fruits, that you wish to update automatically when someone posts something about Fruits. So what you would do is to create a "room" (in Socket.IO terminology) called something like /topics/fruits and have anyone who is viewing this page "subscribe" to this room. Next when anyone posts something about fruits, all you would need to do is "push" this new data to the /topics/fruits room and everyone who is on that view will get the update.

Since you are using grails, here is something to get you pointed towards this: http://compiledammit.com/2012/09/05/websockets-and-grails-broadcasting-to-topics/. For the AngularJS part, you can read up at http://www.html5rocks.com/en/tutorials/frameworks/angular-websockets/ and just implement the Socket.io client part. Just ignore the NodeJS parts on that post.

Solution 3:

The example posted by Eylen works like a charm. In addition, if you want to listen for events in a controller and update a model, here is how you do:

grailsEvents.on('myEvent', function (data) {
    $scope.$apply(function(){
        $scope.mymodel = data.someField;
    });        
});

Post a Comment for "How To Implement Automatic View Update As Soon As There Is Change In Database In Angularjs?"