AngularJS Factory Method (original) (raw)

Last Updated : 19 Oct, 2023

AngularJS Factory Method makes the development process of AngularJS applications more robust. A factory is a simple function that allows us to add some logic to a created object and return the created object. The factory is also used to create/return a function in the form of reusable code which can be used anywhere within the application. Whenever we create an object using a factory it always returns a new instance for that object. The object returned by the factory can be integrated(injectible) with different components of the Angularjs framework such as controller, service, filter, or directive.

Use: A practical Scenario Factory generally acts as a container or class for a collection of functions that fulfills different features of the application. When used with a constructor function it can be initiated within different Controllers.

Syntax:

module.factory( 'factoryName', function(){ Custom code....});

Example 1: The following example illustrates the use of factory code instantiated inside a controller to generate a random number.

HTML `

Factory Example 1