Blog

  • AngularJS Service

    Posted by Ankit Gupta | Last Updated: 11-Dec-15

     

    In this blog, I am going to discuss angular service,an interesting feature of angularJS.
     

    Services provide a way of sharing methods and data among multiple controllers.  An angular service can be injected into multiple controllers and then controllers can use these services.

     

    Example of defining a service :

    angular.module('myApp').service('myService', ['$http', function ($http) {
          
          var myService = {
                  
                 getData: function() {
                   
                 }
                  
          };
          
          return myService;

      }]);

    Here I have created a service myService that has a method getData.

     

    In a service you can have multiple methods which can be called inside controllers. There are some predefined services also which can be used in custom services as well as in controllers.
     

    For example I have used http service of angularJS in my custom service. Generally pre-defined services are used with $ sign and custom services are used without $ sign.

    How to use service in controller :

    angular.module('myApp').controller('myController',['$scope','myService', function($scope,myService){
        $scope.getData = function() {
            myService.getData();
          };
    }]);


     

    Here I have created a controller and used myService.

    Apart from data sharing, angular services also provide some sort of modularity in code.They can be used as a way of dependency management. In angular service we can write server side call and business logic so that controllers can get data ready to render.

     

    Angular service should be developed for each module and written in separate files and all services should be put in service folder.T

     

    Thanks

     

     

Tags: AngularJS