简体   繁体   中英

How attach real-time models to controllers in angular.js?

I'm triying to show several views/controllers with data that come from a real-time json (with pubnub) for a dashboard.

In the angular.js regular docs I see something like:

function CounterCtrl($scope) {
    $scope.data = {'counter':1};
};

But what I want is have a list of datasources, then notify views with the changes of the data and render them.

So, I can have:

counter1:{'counter':1} => Rendered by view1 and view2
counter2:{'counter':5} => Rendered by view3

view4 have not data yet. Some minutes later it arrive

counter3:{'counter':8} => Rendered by view4

Then counter1 is updated

counter1:{'counter':2} 

I create a controller by each view type, some 2 views can be the same controller BUT display different data:

view1 & view3 are UpDownCtrl
view2 is LineGraphCtrl

In the dashboard, I need to update the views, and change the behaviour according to the data (or lack of it, to show a empty state).

PD: I'm open to do this in another js framework if is tailored to this kind of task...

I'm using PubNub as well, and have started a very basic PubNub service in my AngularJS app.

The service (work in progress):

app.factory('pubnub', function($rootScope) {
    var pubnub = {
        lastMessage: '',
        messages: [],
        callback: function(message) {
            pubnub.lastMessage = message;
            pubnub.messages.unshift(message);
            $rootScope.$broadcast('pubnubMessageReceived', message); 
        },
        getLastMessage: function() {
            return pubnub.lastMessage;
        },
        getMessages: function() {
            return pubnub.messages;
        }
    }

    PUBNUB.subscribe({
        channel    : 'my_channel',
        restore    : false, 
        callback   : pubnub.callback,
    });

    return pubnub;
});

One of the (many) controllers:

var ProjectController = function($scope, pubnub) {

    $scope.$on('pubnubMessageReceived', function(event, message) {
        console.log("pubnub message received in project controller",message);
        if(message.target == "project") {
            // The message is for me!! Do something with it
            $scope.data = message.data;
        }
    });
}

So I have one service listening for PubNub messages and broadcasting them over $rootScope, and then it is simple to have any controller listen for those messages. Once you receive a message in your controller, modify your $scope and it will automatically update your view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM