×

Html & Html5

The World's best Software Development Study Portal

AngularJS Services


A service is a function, or object, that is available for, and limited to, your AngularJS application
for example:

  • $location service.

  • $httpservice.

  • $timeout service.

  • $interval service.

  • AngularJS has about 30 built-in services.




  • Example of $location service

          <div ng-app="myApp" ng-controller="myCtrl">
    
          <h3>{{myUrl}}</h3>
          </div>
          <script>
          var app = angular.module('myApp', []);
          app.controller('myCtrl', function($scope, $location) {
          $scope.myUrl = $location.absUrl();
          });
          </script>

    Output
    http://ittrainingclasses.in/learn-angularjs-services.html



    Use a Custom Service Inside a Filter
    Once we created a service, and connected it to our application,
    we use the service in any controller, directive, filter, or even inside other services.
    To use the service inside a filter, add it as a dependency when defining the filter:
    To create your own service, connect your service to the module:

    let's understand with an example
    A custom service with a method:



    converts a 255 number into a hexadecimal number

    
         <div ng-app="myApp" ng-controller="myCtrl">
          <h1>{{hex}}>/h1>
          </div>
          <script>
          var app = angular.module('myApp', []);
          app.service('hexafy', function() {
          this.myFunc = function (x) {
          return x.toString(16);
           }
          });
         app.controller('myCtrl', function($scope, hexafy) {
         $scope.hex = hexafy.myFunc(255);
         });
         </script>
    
    Output
    ff