我正在尝试调用 $http 并将返回的数据分配给一个变量。目前我有这段代码,它运行良好。
这是在我的 Controller 中:
.controller('sample', ['$scope', '$http', function($scope, $http){
var ctrl = this;
$http.get('somejson.json').success(function(data){
$scope.myData = data;
});
});
但是,我不想将它分配给 $scope,而是想将它分配给我的 Controller 变量。但是 ctrl 在我的 get 函数中总是未定义的。我在这里错过了什么吗?我尝试从 Angular 阅读文档,但没有运气。谢谢!
这行不通:
.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?
});
});
最佳答案
它在这个 fiddle 中完美运行。
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?
});
}]);
关于angularjs - 将数据从 http 分配给 'this' Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28933772/