AngularJS Services (Service)

In AngularJS, you can create your own services, or use built-in services.


What is a Service?

In AngularJS, a service is a function or object that can be used in your AngularJS application.

AngularJS has more than 30 built-in services.

There is a$locationservice, which can return the URL address of the current page.

Example

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $location) {
    $scope.myUrl = $location.absUrl();
});

Try it »

Note$locationA service is passed as a parameter to the controller. To use it, you need to define it in the controller.


Why use Services?

Among many services, such as the $location service, it can use objects existing in the DOM, similar to the window.location object, but the window.location object has certain limitations in AngularJS applications.

AngularJS constantly monitors the application and handles event changes. AngularJS uses$locationservices rather than usingwindow.locationobjects, which is better.

$location vs window.location

  window.location $location.service
Purpose Allows read and write operations on the current browser location Allows read and write operations on the current browser location
API Expose an object that can be read and written Expose a jQuery-style reader/writer
Whether integrated with the AngularJS application lifecycle no Can access every stage in the application lifecycle and is integrated with $watch
Whether seamlessly integrated with HTML5 API no Yes (with graceful degradation for older browsers)
Whether related to the application context No, window.location.path returns "/docroot/actual/path" Yes, $location.path() returns "/actual/path"

$http Service

$httpIt is the most commonly used service in AngularJS applications. The service sends requests to the server, and the application responds to the data transmitted by the server.

Example

Use$httpservice to request data from the server:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
    $http.get("welcome.htm").then(function (response) {
        $scope.myWelcome = response.data;
    });
});

Try it »

The above is a very simple$httpservice example. For more$httpservice applications, seeAngularJS Http Tutorial。


$timeout Service

AngularJS $timeoutThe service corresponds to the JS window.setTimeoutfunction.

Example

Display information after two seconds:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $timeout) {
    $scope.myHeader = "Hello World!";
    $timeout(function () {
        $scope.myHeader = "How are you today?";
    }, 2000);
});

Try it »

$interval Service

AngularJS $intervalThe service corresponds to the JSwindow.setIntervalfunction.

Example

Display information every second:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $interval) {
    $scope.theTime = new Date().toLocaleTimeString();
    $interval(function () {
        $scope.theTime = new Date().toLocaleTimeString();
    }, 1000);
});

Try it »

Creating a Custom Service

You can create a custom service and link it to your module:

Create a service namedhexafyservice:

app.service('hexafy', function() {
    this.myFunc = function (x) {
        return x.toString(16);
    }
});

To use a custom service, you need to add it independently when defining the controller and set the dependency:

Example

Use a custom servicehexafyConvert a number to a hexadecimal number:

app.controller('myCtrl', function($scope, hexafy) {
    $scope.hex = hexafy.myFunc(255);
});

Try it »

Using a Custom Service in a Filter

Once you create a custom service and connect it to your application, you can use it in controllers, directives, filters, or other services.

In the filtermyFormatuse the servicehexafy:

app.filter('myFormat',['hexafy', function(hexafy) {
    return function(x) {
        return hexafy.myFunc(x);
    };
}]);

Try it Yourself »

When getting values in an array of objects, you can use filters:

Create a Servicehexafy:

<ul>
<li ng-repeat="x in counts">{{x | myFormat}}</li>
</ul>

Try it Yourself »
Other Extensions