var app = angular.module('GreetingApp',[]); // Define a constant app.constant('constantGreeting', 'Hello'); // Define a provider app.provider('Greeting', function() { this.setName = function(name) { this.name = name; }; this.setConstant = function(constant) { this.constant = constant; }; this.$get = function() { var self = this; return { getGreeting: function() { return self.constant + self.name + "!"; } }; }; }); // Configure the provider with the constant app.config(function(GreetingProvider, constantGreeting){ GreetingProvider.setConstant(constantGreeting); GreetingProvider.setName(' Provider'); }); // Define a value app.value('exclamation', '!'); // Define a factory that uses the constant and value app.factory('GreetingFactory', function(constantGreeting, exclamation) { var greeting = constantGreeting + " Factory" + exclamation; return { getGreeting: function() { return greeting; } }; }); // Define a service that uses the constant and value app.service('GreetingService', function(constantGreeting, exclamation) { var greeting = constantGreeting + " Service" + exclamation; this.getGreeting = function() { return greeting; }; }); // Controller injected with factory, service and provider app.controller('GreetingController', function($scope, GreetingFactory, GreetingService, Greeting) { $scope.factoryGreeting = GreetingFactory.getGreeting(); $scope.serviceGreeting = GreetingService.getGreeting(); $scope.providerGreeting = Greeting.getGreeting(); });
<body ng-app="GreetingApp"> <div ng-controller="GreetingController"> <div>{{ factoryGreeting }}</div> <div>{{ serviceGreeting }}</div> <div>{{ providerGreeting }}</div> </div> </body>