2015-09-21 24 views
0

我试图修改我的控制器的变量,从$ 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; 
    }); 
} 

这里有什么想法?

回答

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

谢谢@JC!这与菲尔的回应相似。然而,你能否评论为什么(如果)这些方法比使用$ scope更受欢迎?我已经看到在线示例中使用$ scope,而我正在研究如何使其发挥作用 – Ricky

+0

使用'$ scope'只是保存对控制器引用的另一种方法。真正的问题是变量'this'。当控制器被实例化时,它指的是控制器,但当执行'$ http'回调时它会变成另一个对象,所以你需要另一种方法来引用该回调中的控制器。如果控制器被附加到'$ scope',例如名为'ctrl'的成员,你可以像这样引用它:'$ scope.ctrl.firstName'。然而,在我看来,这并不比在关闭中明确保存引用清楚。 –

1

的问题是在$http回调this分配给另一个变量,创建不再是你的控制器。

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

https://docs.angularjs.org/api/ng/service/$http#deprecation-notice关于过时$http回调方法。

+0

谢谢@Phil。这工作;也感谢各位领导开始使用“然后”而不是“成功”! – Ricky

+0

@Ricky一些阅读是可在这里〜http://toddmotto.com/digging-into-angulars-controller-as-syntax/ – Phil

-1

更改为在成功函数$范围,使你的代码会像

$scope.firstName = data.firstName; 
$scope.lastName = data.lastName; 

这里面成功函数功能范围不是全球性的范围,以便这不会绑定到控制器。

+0

大概OP是使用*“控制器作为”*表达,因此,暗示他们使用'$ scope'不适用。 – Phil

+0

@Phil:我在这里看到了一些使用这个“$ scope”对象的例子,用Sarjan描述的方式。例如,使用这个$ scope和使用var self = this有什么区别? (然后在内部函数中引用“self”) – Ricky

相关问题