Angular - 修改$ http调用中的控制器变量

时间:2015-09-21 04:38:27

标签: javascript angularjs

我正在尝试从$ 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;
    });
}

这里有什么想法吗?

3 个答案:

答案 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;

此内部成功函数的功能范围不是全局范围,因此不会绑定到控制器。