Service: In Angular JS, a service is a function or object
When writing controller, don't reuse controller. When we have the same code in controller, we need to extract it into a service. All services conform to the principle of dependency injection. Service exists throughout the life cycle of the application and can be used to share data.
Angular provides three ways to create services, factory, service, provider
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> <input type="text" ng-model="name"/> {{name}} </div> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script> var app=angular.module("myApp",[]); //Custom Service provider,myService1 Service name app.provider('myService1', function () { this.$get = function () { return{ message: 'customprovider Message' } } }); //Custom Service service app.service('myService2', function () { return ['Shanghai']; }); //Custom Factory factory app.factory("myService3", [function () { return [1, 2, 3, 4, 5, 6]; }]);
//service is similar to factory, but what is returned must be an object
app.controller('myCtrl',function($scope,myService1,myService2,myService3){ $scope.name = 'A mandarin orange'; console.log(myService1); console.log(myService2); console.log(myService3); }); </script> </body> </html>
Effect screenshots
shared data
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> </head> <body> <div ng-app="myApp"> <div ng-controller="firstCtrl"> <input type="text" ng-model="data.name"/> <input type="text" ng-model="Data.message"/> <p>first{{data.name}}</p> <p>first{{Data.message}}</p> </div> <div ng-controller="secondCtrl"> <p>second{{data.name}}</p> <p>second{{Data.message}}</p> </div> </div> <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script> <script> var app = angular.module("myApp",[]); app.factory('Data',function(){ return{ message:'Shared data' } }); app.controller('firstCtrl',function($scope,Data){ $scope.data ={ name: 'A mandarin orange' }; $scope.Data = Data; }); app.controller('secondCtrl',function($scope,Data){ $scope.Data = Data; }); </script> </body> </html>