[英]Angular bind to the status of a promise?
If I've got a promise from, for example, and HTTP request: 例如,如果我对HTTP请求有一个承诺:
$scope.myHttpPost = $http.post(…);
Is it possible to bind to the status (loading / done / error) in a template? 是否可以绑定到模板中的状态(加载/完成/错误)?
For example, something like: 例如,类似:
<div ng-switch on="myHttpPost.status">
<span ng-switch-when="'loading'">Loading…</span>
<span ng-switch-when="'done'">Success!</span>
<span ng-switch-when="'error'">Error :(</span>
</div>
It doesn't look like you can do this with any built in method. 您似乎无法使用任何内置方法来执行此操作。 However it isn't that hard to setup a reusable promise wrapping system to get the variables you are looking for. 但是,设置可重用的promise包装系统以获取您要查找的变量并不难。 To use the words you wanted in your example, you could do something like: 要在示例中使用您想要的单词,可以执行以下操作:
// function inside service
function newStatus(promise) {
var status = {
label: 'loading'
};
promise.then(function(){
status.label = 'done';
});
promise.catch(function(){
status.label = 'error';
});
return status;
}
Then you set it up where you call $http
like so: 然后将其设置为在调用$http
如下所示:
var promise = $http.post(...);
$scope.httpStatus = Status.newStatus(promise);
Then reference it in your html like so: 然后像这样在您的html中引用它:
<div ng-switch on="httpStatus.label">
<span ng-switch-when="'loading'">Loading…</span>
</div>
You can see it in action here: http://jsfiddle.net/hw0pkgp0/ 您可以在这里查看其运行情况: http : //jsfiddle.net/hw0pkgp0/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.