the*_*fog 5 javascript angularjs
我有简单的角度js控制器,如下所示发出XHR请求
app.controller('MainController', ['$http', function($http) {
this.php_response = {};
var promise = $http.get('process.php');
promise.then(
function(success_data) {
// I dont think "this" is talking to the controller this anymore?
this.php_response = success_data;
}, function(error) {
console.log('there was a problem');
}
);
}]);
Run Code Online (Sandbox Code Playgroud)
当我使用$scope代码而不是代码编写此控制器时,现在该this.php_response属性不包含从XHR请求中检索的数据.
我怀疑promise.then#success回调不再引用控制器this.
如何在promise方法中访问它?
使用保留词汇上下文的箭头函数:
promise.then(success_data => {
this.php_response = success_data;
}, error => {
console.log('there was a problem');
});
Run Code Online (Sandbox Code Playgroud)
另一种简单的方法是使用Function.prototype.bind方法绑定上下文:
promise.then(function(success_data) {
this.php_response = success_data;
}.bind(this), function(error) {
console.log('there was a problem');
});
Run Code Online (Sandbox Code Playgroud)
最后,老派方式:定义指向外部的引用变量this并在回调中使用它:
var self = this;
promise.then(function(success_data) {
self.php_response = success_data;
}, function (error) {
console.log('there was a problem');
});
Run Code Online (Sandbox Code Playgroud)
无论你喜欢什么.
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |