dz210
dz210

Reputation: 768

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//

so that I can bind to it in the HTML and have it dynamically update:

//VIEW//
{{property}}
//VIEW//

However, as you may know, this does not work. The controller.property remains undefined, as this line:

thisService.property = data;

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?

Upvotes: 1

Views: 50

Answers (2)

a better oliver
a better oliver

Reputation: 26828

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.

Plunker

Upvotes: 2

dfsq
dfsq

Reputation: 193251

Another way is to expose service object to the view sos you don't have to make "crazy" stuff to your service:

this.service = ThisService;

and in view use

{{service.property}}

Upvotes: 2

Related Questions