Angularjs 将数据从http分配到';这';控制器
我正在尝试进行$http调用,并将返回的数据分配给变量。目前,我有这个代码,它的工作很好 这是在我的控制器内:Angularjs 将数据从http分配到';这';控制器,angularjs,http,Angularjs,Http,我正在尝试进行$http调用,并将返回的数据分配给变量。目前,我有这个代码,它的工作很好 这是在我的控制器内: .controller('sample', ['$scope', '$http', function($scope, $http){ var ctrl = this; $http.get('somejson.json').success(function(data){ $scope.myData = data; }); }); 但是,我不想
.controller('sample', ['$scope', '$http', function($scope, $http){
var ctrl = this;
$http.get('somejson.json').success(function(data){
$scope.myData = data;
});
});
但是,我不想将其分配给$scope,而是想将其分配给我的控制器变量。但是在我的get函数中,ctrl总是未定义的。我是不是遗漏了什么?我试着从医生的角度看医生,但没有成功。谢谢
这不起作用:
.controller('sample', ['$scope', '$http', function($scope, $http){
var ctrl = this;
$http.get('somejson.json').success(function(data){
debugger;// when I type ctrl in console, just to check, ctrl is undefined.
ctrl.myData = data; // ctrl is undefined. is it possible to do this?
});
});
这把小提琴演奏得很好
app.controller('myController', ['$scope', '$http', function($scope, $http) {
var ctrl = this;
$http.get('https://dl.dropboxusercontent.com/u/94145612/example.json').success(function(data
ctrl.myData = data; // ctrl is undefined. is it possible to do this?
});
}]);
我不确定它为什么不起作用,但我可以几乎完全肯定地说,这不是因为
ctrl
未定义。将此分配给另一个变量应该可以正常工作:
var ctrl = this;
$http.get('somejson.json').success(function(data){
ctrl.myData = data;
});
另一个选项是使用.bind()
:
我喜欢第一种方法
注意:控制台仅使变量可访问
在全局或当前执行函数的范围内
第一例
.controller('sample', ['$scope', '$http', function($scope, $http){
// since it is declared as var ctrl , here it gets function scope.
var ctrl = this;
$http.get('somejson.json').success(function(data){
debugger;
// when application is paused in debugger mode, it will be accessible for that instance
// once debugger mode is gone, console shifts current context, and doesn't make ctrl accessible
ctrl.myData = data;
});
});
第二种情况
.controller('sample', ['$scope', '$http', function($scope, $http){
// since there is no declaration as var ctrl , here it gets global scope.
ctrl = this;
$http.get('somejson.json').success(function(data){
debugger;
// ctrl will be accessible in console
ctrl.myData = data;
});
});
我觉得这很难相信。尝试将值分配给
ctrl.myData
时是否出现错误?这是你的真实代码吗?您的两个代码段中似乎都缺少一个结束语]
。@JLRishe我更新了我的问题。实际上,我有“debugger;”语句要调试。当我点击我的调试器时,我在控制台中键入“ctrl”来查看它是什么值,它说它是未定义的。很好的捕获,但不是问题:)这是不可能的,ctrl在这里有功能范围。在控制台中看不到。如果它是全局变量,则可以获取它。@Nierarshi因此无法将其分配给ctrl.myData?@Nierarshi某些调试器将允许控制台访问暂停执行的当前作用域。但正如我所说的,即使调试器说某些东西是未定义的,但这并不意味着它实际上是未定义的。
.controller('sample', ['$scope', '$http', function($scope, $http){
// since there is no declaration as var ctrl , here it gets global scope.
ctrl = this;
$http.get('somejson.json').success(function(data){
debugger;
// ctrl will be accessible in console
ctrl.myData = data;
});
});