Richard Bender
Richard Bender

Reputation: 1134

Sharing Data in AngularJS Services

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

Upvotes: 0

Views: 1245

Answers (1)

joakimbl
joakimbl

Reputation: 18081

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/

Upvotes: 3

Related Questions