2017-09-21 63 views
-3

现在我有一个控制器并设置如下的一些功能。我想在回调函数中获取变量data2。但现在它是不确定的。在回调函数中无法获得外部变量值

var searchApp = angular.module('reveal.searchUI'); 
 

 
searchApp.controller('SearchController', ['$rootScope','$scope','$q','$http','$timeout','$window', 
 
    '$i18next', '$filter','$sanitize', '$cookies', 
 
    'emcui.EventBus','RemoteUrl',"Reveal","Cache","AUTH_EVENTS", 
 
    function($rootScope, $scope, $q, $http, $timeout, $window, $i18next, 
 
      $filter, $sanitize,$cookies, eventBus,remoteUrlProvider, reveal, 
 
      cache, AUTH_EVENTS){ 
 
     var self = this; 
 
     var data1 = "data1"; 
 
     this.testing = function(){ 
 
      var data2 = "data2"; 
 
      setTimeout(function(){ 
 
      //need to get the variable data2 
 
      },1000); 
 
     }; 
 
    }]);

+4

有没有在你的代码,建议你将不能访问该变量。你确定'''.testing'''实际上在运行吗? – jlogan

+0

使用AngularJS框架,代码应该使用[$ timeout service](https://docs.angularjs.org/api/ng/service/$timeout)而不是原始的'setTimeout'。奇怪的是,控制器注入'$ timeout',但不使用它。你能解释一下吗? – georgeawg

+0

我尝试通过self.testing()来运行它。从调试开始,变量不能被访问。 –

回答

3

代码能够访问data2回调。

确保该示例实际上重现了问题!如果您在编写示例时无意中解决了问题,但没有再次测试它,那么在请求其他人提供帮助之前,您应该知道这一点。

The DEMO

angular.module("app",[]) 
 
.controller('SearchController', [ 
 
    function(){ 
 
     var self = this; 
 
     var data1 = "data1"; 
 
     this.testing = function(){ 
 
      var data2 = "data2"; 
 
      setTimeout(function(){ 
 
      //need to get the variable data2 
 
      console.log(data2); 
 
      },1000); 
 
     }; 
 
}]);
<script src="//unpkg.com/angular/angular.js"></script> 
 
    <body ng-app="app" ng-controller="SearchController as vm"> 
 
    <button ng-click="vm.testing()">Click me</button> 
 
    </body>

相关问题