Providers allow you to share data between different view contexts (aka scopes or controllers).
Another reason why providers are so awesome is that you can chain them together with other providers to create complex, modular logic that is reusable elsewhere.
Types of Providers
There are several different formulas for providers. They are, in increasing order of complexity:
- Constant
- Value
- Factory
- Service
- True Providers
For example, you may want defining to define a Constant representing the hostname / port of a backend service, and create an Angular Service that consumes the Constant to return data from the remote server.
You can then inject then the Service into a Controller to bind to the backend data in a View Template.
angular .module('nameOfModule', []) .constant('HostName', 'localhost') .constant('PortNumber', '4001') .factory('Services', [ '$resource', 'HostName', 'PortNumber', function($resource, HostName, PortNumber) { return $resource('http://' + HostName + ':' + PortNumber + '', {category: 'services', name:'@name'}, { get: {method:'GET', params:{}}, put: {method:'PUT', params:{ 'value':'@value' }}, query: {method:'GET', isArray: true} }) }]) .controller('NameOfController', [ '$scope', 'Services', function($scope, Services) { // Perform a GET (expecting an array result) on http://HostName:PortNumber Services.query(function(a, b, c) { console.log("success!"); $scope.services = a; }, function (a, b, c) { console.log("error!"); }); }]);
The view template can now bind to 'services' to display this data:
<section ng-controller="NameOfController"> <pre>{{ services | json }}</pre> </section>