Search code examples
angularjspolling

Angularjs how to access scope data outside the angular-poller function


I'm pooling data using ng-poller function and then I splice the data/json file. The problem is that if you navigate between the tabs/menu data being spliced each time. All I need to be able to poll the data and then access them outside the function so they are not being spliced every-time you navigate through the site.

here's my controller:

   'use strict';
    angular
        .module('myApp')
        .controller('analyticshistoryCtrl', ['$scope', 'poller', 'Analyticshistory', function ($scope, poller, Analyticshistory) {

            var dataToSplice;
            var pollerAnalyticsHistory;
            pollerAnalyticsHistory = poller.get (Analyticshistory, {delay: 10000});
            pollerAnalyticsHistory.promise.then (null, null, function (data) {


                //this works fine but it splices 
                //data every 10000ms which is not good
                $scope.myData = data.analytics.splice(0,5);


               //I'm trying this to access this outside
               $scope.myData = data.analytics;
               dataToSplice = $scope.myData;

              });

             //outside the poller here I want to access data and splice them
             //to pass them into to ng-grid
             dataToSplice.splice(0,5);//this does not work
             $scope.myData.splice(0,5);//this doe not work either


             $scope.gridOptions = {
                data: 'myData',
                columnDefs: 'columns'
             }
 }]);

Here's the Plunker: http://plnkr.co/edit/ui279rL9JZvxgUJXlkLB?p=preview

Many thanks for your help.


Solution

  • you can check out this plunk - http://plnkr.co/edit/xkQM7NA91JlmHcxat0Qn?p=preview.

    Step 1 : setup an event handler (splice handler) using $scope.$on
    
    Step 2 : call $emit from pollerAnalyticsHistory.promise.then to notify the event handler that data arrives
    
    Step 3 : inside the event handler splice you data and update the grid
    
    Step 4 : unbind the  event handler each time the $scope is destroyed.
    

    Edit: A better and simpler approach (8/18/2014) :

    Step 1 : create a blank scope model ($scope.myData)
    
    Step 2 : add watch on $scope.myData and when ever myData changes, splice it.
    
    Step 3 :  update $scope.myData inside pollerAnalyticsHistory.promise.then
    

    plunk updated : http://plnkr.co/edit/xkQM7NA91JlmHcxat0Qn?p=preview.