现在我有一个控制器并设置一些如下的功能。我想在回调函数中获取变量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);
};
}]);

答案 0 :(得分:3)
代码 能够在回调中访问data2
。
确保该示例实际上重现了该问题!如果您在编写示例时无意中修复了问题但又没有再次测试,那么在询问之前您还是想知道这个问题别人帮忙。
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>
&#13;