Posts

Showing posts with the label Angularjs Factory

AngularJS : When To Use Service Instead Of Factory

Image
Answer : Explanation You got different things here: First: If you use a service you will get the instance of a function (" this " keyword). If you use a factory you will get the value that is returned by invoking the function reference (the return statement in factory). ref: angular.service vs angular.factory Second: Keep in mind all providers in AngularJS (value, constant, services, factories) are singletons! Third: Using one or the other (service or factory) is about code style. But, the common way in AngularJS is to use factory . Why ? Because "The factory method is the most common way of getting objects into AngularJS dependency injection system. It is very flexible and can contain sophisticated creation logic. Since factories are regular functions, we can also take advantage of a new lexical scope to simulate "private" variables. This is very useful as we can hide implementation details of a given service." ( ...

AngularJS : Factory And Service?

Image
Answer : Service vs Factory The difference between factory and service is just like the difference between a function and an object Factory Provider Gives us the function's return value ie. You just create an object, add properties to it, then return that same object.When you pass this service into your controller, those properties on the object will now be available in that controller through your factory. (Hypothetical Scenario) Singleton and will only be created once Reusable components Factory are a great way for communicating between controllers like sharing data. Can use other dependencies Usually used when the service instance requires complex creation logic Cannot be injected in .config() function. Used for non configurable services If you're using an object, you could use the factory provider. Syntax: module.factory('factoryName', function); Service Provider Gives us the instance of a function (object)- You just instantiated wi...