user2024080 user2024080 - 4 months ago 13
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) {
$scope.name = 'World';
});

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

//type 2
angular.module('MyApp')
.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

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';

angular
    .module('app')
    .factory('logger', logger);

function logger() { }
})();