$ http.get和控制器之间的角度共享变量 [英] Angular Share Variable betwen $http.get and controller
本文介绍了$ http.get和控制器之间的角度共享变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法将$http.get()
内部的一个变量的内容传递给此方法的外部...它始终是undefined
.
I can't pass the content of one variable inside $http.get()
to outside of this method... it's always undefined
.
我在$rootScope
上进行了测试,但是没有用.
I tested with $rootScope
, but it didn't work.
controller('myControl', function ($scope, $http) {
var content;
$http.get('../Json/data.json').success(function (data, content) {
content = data;
}).error(function (data, status, headers, config) {
$scope.dataJson = "ERROR";
});
console.log(content);
});
推荐答案
这里有两个问题:
- 成功处理程序中的
content
参数是 shadowing 控制器中的content
变量. - 您正在尝试将
content
写入控制台,直到它具有一个值.这将不起作用,因为$http.get()
是异步的.
- The
content
parameter in your success handler is shadowing thecontent
variable in your controller. - You are trying to write
content
to the console before it has a value. This will not work because$http.get()
is asynchronous.
要解决这些问题:
- 删除
content
参数.它没有任何目的. - 在
success
回调中使用content
变量 .
- Remove the
content
parameter. It serves no purpose. - Use the
content
variable inside yoursuccess
callback.
controller('myControl', function ($scope, $http) {
var content;
$http.get('../Json/data.json').success(function (data) {
content = data;
console.log(content);
$scope.dataJson = content;
}).error(function (data, status, headers, config) {
$scope.dataJson = "ERROR";
});
});
这篇关于$ http.get和控制器之间的角度共享变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文