如何设置在JavaScript函数内的值到全局变量/角? [英] How to set a value to a global variable inside a function in javascript/angular?
问题描述
好吧,我需要使用不同的角度控制器或任何功能,我可以做一个变量,但是在这种特殊情况下我碰到一个服务或函数的变量之一的值,你想怎么称呼它,这是code
Well, I need to use a variable in different angular controllers or any function, which I can do, but in this particular case I'm getting the value of one of those variables from a service or a function, how you want to call it, this is the code
//global variable userdata
userdata = {};
ng.tcts.service('$user', function($http, $q, $window, $boots){
return{
login: function(data){
var deferred = $q.defer();
$http({
method:'POST',
url:ng.api+'/log/in',
data:{
data:data
},
headers:{'Content-type':'application/x-www-form-urlencoded'}
}).success(function(response, status, headers, config){
if(response.success){
console.log(response);
//userdata assignation
userdata = response.data;
deferred.resolve([response.respnum, response.success, response.report, response.data]);
}
else{
deferred.resolve([response.respnum, response.success, response.report, response.data]);
}
}).error(function(response, status, headers, config){
deferred.reject([response.respnum, response.success, response.report]);
});
return deferred.promise;
}
);
正如你可以看到我asigining用户数据的成功函数内部response.data的价值,当我使用它的功能环境它的工作原理,在分配工作正常,但是当我尝试使用它之外呢,对象是空的,我希望你能帮助我,THX
As you can see I'm asigining userdata the value of response.data inside the success function , when I use it in the function environment it works , the assignation works fine, but when I try to use it outside of it, the object is empty, I hope you can help me with this, thx
推荐答案
所有你需要做的是使该得到一个服务,并设置用户数据和数据保持在服务中。然后,你作出这样的返回数据的方法,你可以把它注射到你的应用程序的任何控制器。
all you need to do is make a service that gets and set the user data and the data is kept inside the service. Then you make a method that returns that data and you can inject it into any controller in your app.
app.service('userData',function(){
var data;
this.get = function() {
// do your ajax call to get your user data and in the response data = response;
}
this.data = function() {
return data;
}
});
在任意一个控制器:
then in any controller:
function myCtrl($scope,userData) {
// you can access it with this userData.data();
// or set it to a $scope var
$scope.userData = userData.data();
}
制作一个全局变量是不是您如何使用角度,您可以创建一个服务,你再注入到你的控制器,因此多个地方可以跟这些数据,也可以将其设置为$ rootScope变种,然后在任何引用它控制器。从不创建一个全局变量,并在控制器中引用它虽然。这是你如何最终在角内存泄漏。
Making a global variable isn't how you use Angular you can create a service that you then inject into your controllers so multiple places can talk to that data or you can set it to a $rootScope var and then reference it in any controller. NEVER create a global variable and reference it in your controller though. This is how you end up with memory leaks in Angular.
这篇关于如何设置在JavaScript函数内的值到全局变量/角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!