Dou*_*oug 7 javascript angularjs angularjs-http
我对整个AngularJS世界以及它是如何工作都很陌生,但是我很难让它按预期工作.我知道它与我使用的方式有关,$http.get()
并试图将变量分配回我的控制器,但我无法弄明白.
使用$scope
而不是this
我可以使它工作,但如果可能的话,我更喜欢使用this
所以我可以使用"控制器作为"
码:
app.controller('ctrlSuppliers', function($http){
this.supplierList = {};
$http.get("http://some_url_here")
.success(function(response) { this.supplierList = response.records;})
.error(function() { this.supplierList = [{supplier_id: 0, supplier_name: 'Error Getting Details'}];});
});
Run Code Online (Sandbox Code Playgroud)
从这个例子中,我无法$http.get
从supplierList
HTML页面内部访问请求中的{{ supplier.supplierList[0].supplier_name }}
任何结果(即不显示任何结果)
我知道如果我将控制器更改为$scope
可以访问该数据(虽然不使用与上面相同的格式),并且我也知道通过console.log(this.supplierList)
在.success
调用中使用来填充数据.
我也知道它不工作的原因是因为this
从控制器内到$http.get
调用内的变化的上下文.
所以我的问题是:如何使用this
而不是使用$ http.xxx调用来访问结果scope
?我已经阅读了一些不同的消息来源,但大多数人都在谈论使用$scope
和承诺.我没有发现任何封面使用this
(或声明它var supplier = this
).任何帮助将非常感激.
谢谢,
始终存储变量引用,this
以便您没有上下文问题,然后使用该变量而不是this
整个控制器
app.controller('ctrlSuppliers', function($http){
var vm = this;
// now can forget using "this" and use variable instead
vm.supplierList = {};
$http.get("http://some_url_here") .success(function(response) {
// no context issues since "vm" is in scope
vm.supplierList = response.records;
});
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8843 次 |
最近记录: |