Angularjs如何在angular-poller函数之外访问范围数据

时间:2014-08-18 08:56:37

标签: angularjs polling

我使用ng-poller函数汇集数据,然后拼接data / json文件。问题是,如果您在每次拼接的选项卡/菜单数据之间导航。我需要能够轮询数据,然后在函数外部访问它们,这样每次浏览网站时都不会拼接它们。

这是我的控制人员:

   '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'
             }
 }]);

这里是Plunker:http://plnkr.co/edit/ui279rL9JZvxgUJXlkLB?p=preview

非常感谢你的帮助。

1 个答案:

答案 0 :(得分:1)

你可以查看这个插件 - 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.

编辑:一种更好,更简单的方法(2014年8月18日):

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已更新:http://plnkr.co/edit/xkQM7NA91JlmHcxat0Qn?p=preview