1

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?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Yes but is this really better? This adds all the properties of the service to be watched and accessed, but I only want to access some of them. Is there any performance hit with doing this?
I would say that it's not that bad actually. Nothing gets copied it's just a reference. In addition there are no additional watchers set up for service properties in this case. Performance hit is minimal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.