| Start |
|---|
| Creating a service using angular.factory First define the service (in this case it uses the factory pattern): Now you can use the service to share data between controllers: |
How to create a Service |
How to use a service In the template using this controller you'd then write: or Of course, in real code you would interact with the service using methods on the controller, which in turn delegate to the service. The example above simply increments the counter value each time the controller is used in a template. Services in Angularjs are singletons: Services are singleton objects that are instantiated only once per app (by the $injector) and lazy loaded (created only when necessary). A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. [As stated here](http://stackoverflow.com/questions/2155688/what-is-a-singleton-in-c) |
| $sce - sanitize and render content and resources in templates $sce ("Strict Contextual Escaping") (opens new window) is a built-in angular service that automatically sanitize content and internal sources in templates. injecting external sources and raw HTML into the template requires manual wrapping of In this example we'll create a simple $sce sanitation filter :`. Usage in template |
| Difference between Service and Factory 1) Services A service is a There is one thumb rule to remember in case of services
Lets see a simple example where we would register a service which uses We just inject this service into the controller When to use? Use 2) Factory Even though we can achieve all the things using A There are two thumb rules to remember in case of factories
Lets see some examples on what we can do using Returning Objects Literals Lets see an example where factory is used to return an object using a basic Revealing module pattern Usage inside a controller Returning Closures What is a closure? Closures are functions that refer to variables that are used locally, BUT defined in an enclosing scope. Following is an example of a closure The "wonderful" part is that it can access the Lets use the above closure example inside Usage inside a controller Creating Constructors/instances
Lets see an example on how to achieve this Usage inside a controller |
How to create a Service with dependencies using 'array syntax' |
| Registering a Service The most common and flexible way to create a service uses the angular.module API factory: The service factory function can be either a function or an array, just like the way we create controllers: To expose a method on our service, we can place it as an attribute on the service object. |
Read Article
https://develop.horje.com/learn/1434/reference