0

I've been using services in AngularJS to share data between controllers. In one particular service, I want to also expose some functionality to edit the shared object. I created a simplified JSFiddle here:

http://jsfiddle.net/RichardBender/CQ6Z4/2/

angular.module('myApp', [])
.factory('myService', function() {
    return {
        mySharedObject:{
            myText:'abc'
        },
        updateObject: function() {
            console.log('function called');
            console.log(this);
            this.mySharedObject.myText = 'def';
        }
    };
})

I can see that the "this" when I call updateObject() is not the object literal that the service returns. I realize that I could simply make this service depend upon another service that just exposes the shared data object, but is there a way to do so without creating a second service?

Thanks, Richard

1 Answer 1

3

The this keyword in javascript can be a bit confusing, as in most cases its value is determined by how the function was called. There are many good articles on the internet that describes this behavior (this one seems pretty good).

I usually do something like this in my services - var myService in the service factory is now the same object that you can inject in your other services:

.factory('myService', function() {
  var myService = {
    mySharedObject:{
        myText:'abc'
    },
    updateObject: function() {
        console.log('function called');
        console.log(this);
        myService.mySharedObject.myText = 'def';
    }
  };
  return myService;
})

I've updated your example to show you how you get the expected value from this and a simple solution to how you can avoid using this: http://jsfiddle.net/sRb2N/

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

2 Comments

Thanks a lot, that worked perfectly. I'm still a bit hazy on "this" so I appreciate the article link.
If you find the "this" behavior confusing, you might consider using Coffeescript. They introduce two operators (-> and =>) the latter of which automatically does what joakimbl is doing above. That way, you can count on "this" being defined to match "this" where the function is defined, not where it's being called from.

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.