Angularjs如何从外部访问范围数据

时间:2014-08-14 11:30:56

标签: angularjs angularjs-scope scope ng-grid

我有这个轮询函数,每10000毫秒轮询数据,这很好,但我需要能够从外部访问变量,以便我可以使用splice函数。

服务代码:

'use strict';
//service to get data for analytics page
angular
    .module ('myApp')
    .factory('Analyticshistory', function ($resource) {
        return $resource('analytics_history.json',{}, {'query': {method: 'GET', isArray: false}});
      });

控制器代码:

   '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

2 个答案:

答案 0 :(得分:1)

看起来像poller.get是异步调用。所以当你调用dataToSplice.splice(0,5)时; dataToSplice中可能没有数据。

这就是为什么拼接不能在promise.then()

之外工作的原因
  

//在轮询器外面我想访问数据并将它们拼接到//   将它们传递给ng-grid dataToSplice.splice(0,5); //这不是   work $ scope.myData.splice(0,5); //这个不能正常工作

现在你有两个选择 -

  1. 继续您的选择方式1

  2. 或设置一个单独的事件处理程序(这可以在同一个Controller或另一个控制器中完成)并在pollerAnalyticsHistory.promise中调用$ emit。然后

  3. 查看我关于如何处理事件的帖子(通过$ on和$ emit) Angular Js newbie - link in a controller view that triggers another controller action

    编辑:(这应该有用) -

    angular
        .module('myApp')
        .controller('analyticshistoryCtrl', ['$rootScope', '$scope', 'poller', 'Analyticshistory', function ($rootScope, $scope, poller, Analyticshistory) {
    
    
    $rootScope.$on("SpliceHandler", function(evt, next, current) {
               $scope.myData.splice(0,5);
    }
    
    pollerAnalyticsHistory.promise.then (null, null, function (data) {
    
               //I'm trying this to access this outside
               $scope.myData = data.analytics;
               dataToSplice = $scope.myData;
    
    $scope.$emit("SpliceHandler");
    }
    
    }]);    
    

    编辑(2014年8月16日): 点击此处:http://plnkr.co/edit/xkQM7NA91JlmHcxat0Qn?p=preview

    编辑(2014年8月18日): 忘了解开听众的束缚。 plunk更新。

答案 1 :(得分:0)

您可以在服务中使用$ rootscope.broadcast,然后通过$ scope.on在控制器中监听它。