我正在尝试从$ http(从API接收数据)的调用中修改我的控制器变量。这些控制器变量在我的视图中与ng-model绑定。
然而,它不起作用 - 什么都没有显示!
angular
.module('myApp')
.controller('contactController', ['$scope', '$http', ContactController]);
function ContactController($scope, $http) {
this.firstName = '';
this.lastName = '';
$http.get('../server/getdata').success(function(data) {
// I would like to set the firstName and lastName variables
// from the above parent scope into here. Is this possible?
this.firstName = data.firstName;
this.lastName = data.lastName;
});
}
这里有什么想法吗?
答案 0 :(得分:1)
只需在创建捕获时保留this
的值,方法是将其分配给另一个变量,例如self
angular
.module('myApp')
.controller('contactController', ['$scope', '$http', ContactController]);
function ContactController($scope, $http) {
var self = this;
this.firstName = '';
this.lastName = '';
$http.get('../server/getdata').success(function(data) {
// I would like to set the firstName and lastName variables
// from the above parent scope into here. Is this possible?
self.firstName = data.firstName;
self.lastName = data.lastName;
});
}
答案 1 :(得分:1)
问题是this
回调中的$http
不再是您的控制者。
将this
值分配给范围变量,例如
var ctrl = this;
ctrl.firstName = '';
ctrl.lastName = '';
// keep in mind the "success" and "error" methods on the $http promise
// have been deprecated. Use the standard "then" method instead.
$http.get('../server/getdata').then(function(response) {
ctrl.firstName = response.data.firstName;
ctrl.lastName = response.data.lastName;
});
有关已弃用的$http
回调方法,请参阅https://docs.angularjs.org/api/ng/service/$http#deprecation-notice。
答案 2 :(得分:-1)
将此更改为成功函数中的$ scope,因此您的代码将类似于
$scope.firstName = data.firstName;
$scope.lastName = data.lastName;
此内部成功函数的功能范围不是全局范围,因此不会绑定到控制器。