2017-09-21 64 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>

相關問題