![]() |
VOOZH | about |
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.
Output:
👁 ImageOn Clicking the generate random number button we get a different number every time. In this example, we use the factory method to define a function that carries a variable and using the Math.random we store a random value to that variable every time this function is called. This function is then called in the controller whose $scope variable carries the random value from the called function we then call this controller to our HTML code to display the result.
Example 2: This example makes use of a factory to create a function to find the addition or subtraction of two numbers. this function is then loaded in the controller $scope variable which passes them to the HTML code for displaying the results.
Output:
👁 Image