gpt4 book ai didi

javascript - Angular - 修改 $http 调用中的 Controller 变量

转载 作者:行者123 更新时间:2023-12-03 08:50:41 25 4
gpt4 key购买 nike

我正在尝试通过调用 $http(从 API 接收数据)来修改 Controller 的变量。在我看来,这些 Controller 变量与 ng-model 绑定(bind)在一起。

但是,它不起作用——什么也没有显示!

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;
});
}

这里有什么想法吗?

最佳答案

只需在创建捕获时保留 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;
});
}

关于javascript - Angular - 修改 $http 调用中的 Controller 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32687455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com