init fail
init fail

Reputation: 399

How do I properly extend an angularJS factory

If I have some base factory that has a bunch of methods I want to extend to a bunch of other factories such as

function TestFactory() {

    var service = {};

    service.name = null
    service.lastname = null

    service.screech = function() {
       alert(service.name + service.lastname)
    }

    return service;

}

And I want to extend that functionality to another service such as

function NewFactory() {

    var service = angular.copy(TestFactory)

    service.name = 'Cool'
    service.lastname = 'Guy'

    return service;

}

I would expect NewFactory.screech() to alert "CoolGuy", but it appears it is calling the screech method in the scope of the original TestFactory where name and lastname are null.

How can I accomplish this pattern?

I have also tried using angular.extend but had the same result.

Upvotes: 2

Views: 139

Answers (2)

Amit Dhaka
Amit Dhaka

Reputation: 178

Change service variable to this. Closure will bind the service variable to the function instead service should be using scope of the object so that it can be inherited.

All functions inside the factory should be using this to refer the object.

function TestFactory() {

    var service = {};

    service.name = null
    service.lastname = null

    service.screech = function() {
       alert(this.name + this.lastname)
    }

    return service;

}

Also change the following code to return the factory object not the Factory Function

function NewFactory() {

    var service = angular.copy(TestFactory())

    service.name = 'Cool'
    service.lastname = 'Guy'

    return service;

}

Upvotes: 2

Rory O'Kane
Rory O'Kane

Reputation: 30398

Change service to this inside the definition of service.screech:

service.screech = function() {
   alert(this.name + this.lastname)
}

It didn't work because when you referred to service inside the function, due to closure, service was hard-coded to the service object at the time of definition. The reference was not updated when you made the copy. this, on the other hand, is dynamic and always refers the the object that the function is being called on, e.g. with service.screech().

Also, you need to set service to a copy of the object resulting from the TestFactory, not to a copy of the TestFactory itself:

var service = angular.copy(TestFactory())

Upvotes: 2

Related Questions