我试图修改我的控制器的变量,从$ 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;
});
}
这里有什么想法?
谢谢@JC!这与菲尔的回应相似。然而,你能否评论为什么(如果)这些方法比使用$ scope更受欢迎?我已经看到在线示例中使用$ scope,而我正在研究如何使其发挥作用 – Ricky
使用'$ scope'只是保存对控制器引用的另一种方法。真正的问题是变量'this'。当控制器被实例化时,它指的是控制器,但当执行'$ http'回调时它会变成另一个对象,所以你需要另一种方法来引用该回调中的控制器。如果控制器被附加到'$ scope',例如名为'ctrl'的成员,你可以像这样引用它:'$ scope.ctrl.firstName'。然而,在我看来,这并不比在关闭中明确保存引用清楚。 –