user2024080 user2024080 - 1 year ago 65
AngularJS Question

Angularjs - What is the correct way to create `factory` and how to use them?

I am very new to angular, I would like to understand the factory method.

I tried to create a factory method to my app with different ways. but nothing works for me - why?

as well which is the correct way to create factory methods and do we have multiple ways to create factory methods ? - if so please explain with their advantages and disadvantages ?

here is my try :

var app = angular.module('MyApp', ['authService' ]);

app.controller('MainCtrl', function($scope) {
$ = 'World';

//type 1
app.factory('appFactory', function(){
console.log(" called from app factory")

//type 2
.factory( 'myFactory', function(){

console.log("called from factory");


//type 3
angular.module("authService", [])

.factory("Auth", function( $http, $q, AuthToken ) {

console.log(" i am called from auth factory")


Live Demo

Answer Source

Here is a forked version of your plunker

  • Your factory must return something. Check out the return statement in the plunker
  • You should inject the factory in your controller MainCtrl for the factory to be initialized. That's why the console.logs were not printed.

Optimal usage of factory/services

According to the widely used John Papa's angular 1 style guide below is the optimal approach. Read more about angular guidelines on the style guide

(function() {
'use strict';

    .factory('logger', logger);

function logger() { }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download