---
title: "Angular JS custom Services Example."  
description: "Angular JS custom Services Example."  
author: "Sandra Emily"  
published: 2024-06-24  
updated: 2024-06-25  
canonical: https://www.mindstick.com/forum/160778/angular-js-custom-services-example  
category: "angular js"  
tags: ["web development", "angular js", "front-end development"]  
reading_time: 2 minutes  

---

# Angular JS custom Services Example.

[Angular](https://www.mindstick.com/articles/13081/advantages-disadvantages-of-angularjs-is-that-ideal-for-your-project) JS custom Services Example.

## Replies

### Reply by Ravi Vishwakarma

[**Creating custom services**](https://www.mindstick.com/forum/160773/explain-angularjs-services-with-examples) in AngularJS is a way to encapsulate **reusable code**, **such as business logic**, **data retrieval**, or utility functions, making them available across your application.

You can create and use custom services using different methods: `service`, `factory`, and `provider`.

## Step 1: Define the AngularJS module and service

```javascript
var app = angular.module('myApp', []);

app.service('MathService', function() {
    this.add = function(a, b) {
        return a + b;
    };
    this.subtract = function(a, b) {
        return a - b;
    };
});
```

## Step 2: Use the service in a controller

```javascript
app.controller('MainController', ['$scope', 'MathService', function($scope, MathService) {
    $scope.addition = MathService.add(5, 3);      // 8
    $scope.subtraction = MathService.subtract(5, 3);  // 2
}]);
```

## Step 3: Create the HTML to use the controller

```html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>Service Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="MainController">
    <p>Addition: {{ addition }}</p>
    <p>Subtraction: {{ subtraction }}</p>
</body>
</html>
```

## Note

- **Service**: Uses a constructor function to create a singleton service. It’s suitable for simple services.
- **Factory**: Returns an object or a function. It’s more flexible than a service.
- **Provider**: Provides the most flexibility. It allows configuration during the configuration phase of the application.


---

Original Source: https://www.mindstick.com/forum/160778/angular-js-custom-services-example

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
