AngularJS:设置属性,同时保持绑定:有没有更好的办法? [英] AngularJS: Setting properties while keeping a binding: is there a better way?
问题描述
如果我有一个服务的一些属性,我想设置为我从一个网络调用回数据,我可以做这样的事情:
If I have some property in a service that I want to set equal to the data I get back from a network call, I can do something like this:
//SERVICE//
thisService.property = data;
//SERVICE//
在我的控制,我可以做的:
and in my controller I can do:
//CONTROLLER//
this.property = ThisService.property;
//CONTROLLER//
这样我可以绑定到它的HTML和有它动态更新:
so that I can bind to it in the HTML and have it dynamically update:
//VIEW//
{{property}}
//VIEW//
然而,正如你可能知道,这是行不通的。该controller.property仍然是不确定的,因为这行:
However, as you may know, this does not work. The controller.property remains undefined, as this line:
thisService.property = data;
将创建thisService.property一个新的参考,而旧人,在控制器中设置,将不指向新的数据。
will create a new reference for thisService.property, and the old one, set in the controller, will not point to the new data.
所以,我要做的就是在包装另一个对象的数据,做这样的事情:
So, what I have to do is wrap the data in another object, and do something like this:
//SERVICE//
thisService.property = {};
thisService.property.property = data;
//SERVICE//
//CONTROLLER//
this.property = ThisService.property;
//CONTROLLER
//VIEW//
{{property.property}}
//VIEW//
这是相当粗糙和丑陋。是否有实现这一目标的一个更好,更清洁的方式?
This is rather crude and ugly. Is there a better, cleaner way of achieving this?
推荐答案
创建一个getter。
Create a getter.
Object.defineProperty(this, 'property',
{ get: function() { return ThisService.property; }});
现在控制器的属性
总是引用当前服务的属性
。
Now the controller's property
will always refer to the current service's property
.
如果该服务的值设置只有一次,不会再发生变化,那么我建议你使用一个承诺,虽然。这将告诉更多关于发生了什么。
If the service's value is set only once and never changes again, then I'd recommend using a promise though. That would tell more about what's going on.
这篇关于AngularJS:设置属性,同时保持绑定:有没有更好的办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!