badigard badigard - 1 year ago 61
Javascript Question

Use Javascript Object to Angular Service

I am trying to add functions to a JS Object which will be used as a singleton service.

angular
.module('app.steps')
.factory('createStepsService', createStepsService);

createStepsService.$inject = [];

/* @ngInject */
function createStepsService() {
var steps;

var service = {
newSteps: function (current_step, total_steps) {
if (!steps) {
return new Steps(current_step, total_steps);
}
}
};
return service;

function Steps(current_step, total_steps) {
this.c_step = current_step;
this.t_step = total_steps;
}

Steps.prototype = {
addSteps: function (num) {
this.c_step += num;
},
setLastStep: function () {
this.lastStep = this.c_step = this.t_step;
}
};
}


When I run this line from the controller, I am not able to access
addSteps / setLastStep methods.

vm.createStepsService = createStepsService.newSteps(1, 3);


Why I don't see these methods? Were they created?

Thanks.

Answer Source

Your steps.prototype code is never ran.

This is because it appears after the return.

Change the order of your code to this:

/* @ngInject */
function createStepsService() {
    var steps;

    function Steps(current_step, total_steps) {
        this.c_step = current_step;
        this.t_step = total_steps;            
    }

    Steps.prototype = {
        addSteps: function (num) {
            this.c_step += num;
        },
        setLastStep: function () {
            this.lastStep = this.c_step = this.t_step;
        }
    };

    var service = {
        newSteps: function (current_step, total_steps) {
            if (!steps) {                   
                return new Steps(current_step, total_steps);
            }
        }            
    };       

    return service; 
}

The reason that you can have a function declared before a return is because of JavaScript variable and function hoisting.