1

I am building an app which aggregates data provided by Facebook GRAPH live. Specifically I want to read the number of likes from various Facebook pages and display a total number of likes. This information is being updated every 5 seconds. I have managed to pull in and update information from individual pages but can not figure out how to add these values together and display the total number. Here is the markup:

<div ng-controller="TotalController">
    <span ng-controller="UpdateController" ng-init="init('331288023558058','fan_count')">{{output}}</span>
    <span ng-controller="UpdateController" ng-init="init('20531316728','fan_count')">{{output}}</span>
    <span>{{outputTotal}}</span>   
</div>

and here is the script for it:

var app = angular.module('app', []);

app.controller('UpdateController', function($scope, $http) {

$scope.init = function(id, item) {
    $scope.id = id;
    $scope.item = item;        

    //retrieve data on the initial load
    $scope.updateData();

};

$scope.updateData = function() {

    $http({
        method: 'JSONP',
        url: 'https://graph.facebook.com/fql?q=select ' + $scope.item + ' from page where page_id = ' + $scope.id + '&callback=JSON_CALLBACK'
    }).success(function(data) {

        //load the new value
        var currentValue = data['data'][0][$scope.item];

        //output new value to view
        $scope.output = currentValue;

    }).error(function(data, status) {
        console.log("error " + data + " " + status);
    });
};

var timer = setInterval(function() {
    $scope.$apply($scope.updateData);
}, 5000);

});

I have tried setting up a controller which encompasses the two Update controllers and watching the scope for changes but I couldn't get the data out of the two child controllers.

My understanding is that the best way to go about it would be to set up a service which aggregates the values, and then inject this service into a third 'Total' controller, but I haven't been able to implement this either. What would be the best way to tackle this problem? Is my approach with controllers completely wrong?

  • 4
    as soon as you see need to share data across controllers, store the data in a service and inject service in controllers. Use service to make http calls also. Then by inheritance they share same arrays, objects etc – charlietfl Nov 15 '13 at 17:25
  • In addition to the comment by @charlietfl, you may also want to use Angular's wrapper for setInterval, which is the [$timeout](http://docs.angularjs.org/api/ng.$timeout) service. This will ensure a digest cycle is trigger at each interval. See [this other post](http://stackoverflow.com/questions/16066239/defer-angularjs-watch-execution-after-digest-raising-dom-event) for a few comments about this. – jelinson Nov 18 '13 at 03:11

0 Answers0