AngularJS – Step 10: Factories

In AngularJS, a Factory is a type of Service that returns an object, function, or value to other parts of your application. Factories are useful for organizing and sharing code across multiple components or controllers in your application.

Here’s a comparison table between Factories and Services:

FactoriesServices
ReturnsAn object, function or valueA new instance of the constructor function
SingletonNo, new instance every time it is injectedYes, only one instance per injector
UsageCreating singletons or returning objects, functions or valuesCreating objects, functions or values that need to be instantiated multiple times
DefinitionDefined using the factory method of the module objectDefined using the service method of the module object

Here’s an example of how to create a Factory in AngularJS:

angular.module('myApp', [])
  .factory('myFactory', function() {
    var factory = {};
    factory.sayHello = function() {
      return "Hello World!";
    };
    return factory;
  });

In this example, we’re creating a factory called myFactory that returns an object with a method sayHello that returns the string “Hello World!”.

We can then use this factory in other parts of our application like this:

angular.module('myApp')
  .controller('myController', function($scope, myFactory) {
    $scope.message = myFactory.sayHello();
  });

In this example, we’re injecting the myFactory factory into a controller called myController and using the sayHello method to set the $scope.message variable to “Hello World!”.

Overall, Factories are a great way to create reusable code in your AngularJS application.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.