Programming Tutorials

AngularJS Services Example: Create and Inject Services (Legacy Guide)

AngularJS services let you move reusable logic out of controllers and share it through dependency injection (DI). In this tutorial, you will create two small services—one that squares a number and another that multiplies two numbers—and inject both into a single controller.

Important maintenance note: AngularJS 1.x is a legacy framework. Official support ended in January 2022, and the AngularJS GitHub repository was archived in April 2024. This example is intended for learning the service pattern or maintaining an existing AngularJS application; it is not a recommendation for a new project. The actively supported Angular framework is a separate, newer framework.

Advertisement

What is an AngularJS service?

An AngularJS service is a reusable object or value registered with an AngularJS module and made available through the dependency-injection system. A controller, directive, filter or another service can request it by name instead of creating its own copy of the logic.

AngularJS services have two useful characteristics:

Advertisement
  • Lazy instantiation: the injector creates a service when something first requests it.
  • Singleton behaviour: within an injector, dependent components receive the same service instance rather than a new instance every time.

This makes services useful for shared calculations, data access, validation, logging and other logic that should not be duplicated across controllers.

What you will build

The example contains two services:

  • squareService exposes a square() method that returns a number multiplied by itself.
  • multiplicationService exposes a multiply() method that multiplies two numbers.

Both services are registered in a separate module named calculator.services. The main application module, mainApp, depends on that module and injects the two services into one controller.

AngularJS Service Example
Original example screenshot from the earlier tutorial; the interface is illustrative.

1. Include AngularJS and create the HTML page

For this legacy demonstration, the example uses AngularJS 1.8.3 from cdnjs. The library is no longer supported by the AngularJS project. If you are maintaining an existing application, use a dependency source and version approved for that application rather than adding an old framework to a new production project.

Create an index.html file. Load AngularJS before your application script so the angular object exists when your module is registered.

<!doctype html>
<html lang="en" ng-app="mainApp">
<head>
    <meta charset="utf-8">
    <title>AngularJS Services Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-controller="myController">

    <h2>Square Service</h2>
    <label for="squareNumber">Enter a number:</label>
    <input id="squareNumber" type="number" step="any" ng-model="squareNumber">
    <button type="button" ng-click="calculateSquare()">Calculate square</button>
    <p aria-live="polite">Result: {{ squareResult }}</p>

    <hr>

    <h2>Multiplication Service</h2>
    <label for="firstNumber">First number:</label>
    <input id="firstNumber" type="number" step="any" ng-model="firstNumber">

    <label for="secondNumber">Second number:</label>
    <input id="secondNumber" type="number" step="any" ng-model="secondNumber">

    <button type="button" ng-click="calculateProduct()">Multiply</button>
    <p aria-live="polite">Result: {{ productResult }}</p>

</body>
</html>

The ng-app attribute tells AngularJS which module starts the application. The ng-controller attribute connects the page to the controller. Each ng-model binds an input to a scope property, while ng-click calls the relevant controller function.

2. Create the two services

Create an app.js file in the same folder as index.html. First, register the square and multiplication services in the calculator.services module. Keep the immediately invoked function open; the controller is added in Step 3 and the function is closed at the end of that code.

(function () {
    'use strict';

    angular.module('calculator.services', [])
        .service('squareService', SquareService)
        .service('multiplicationService', MultiplicationService);

    function SquareService() {
        this.square = function (number) {
            return number * number;
        };
    }

    function MultiplicationService() {
        this.multiply = function (first, second) {
            return first * second;
        };
    }

    // The main application and controller are registered below.

Here, .service() registers a constructor function. AngularJS creates the service instance and exposes the methods assigned to this. The names used during registration—squareService and multiplicationService—are the names that other components request through dependency injection.

3. Register the service module with the main application

The main application must declare calculator.services as a dependency. Add the controller registration and controller function to the same app.js file, before the closing function call:

angular.module('mainApp', ['calculator.services'])
    .controller('myController', MyController);

MyController.$inject = [
    '$scope',
    'squareService',
    'multiplicationService'
];

function MyController($scope, squareService, multiplicationService) {

    $scope.calculateSquare = function () {
        if (typeof $scope.squareNumber !== 'number' ||
            !isFinite($scope.squareNumber)) {
            $scope.squareResult = 'Enter a valid number.';
            return;
        }

        $scope.squareResult =
            squareService.square($scope.squareNumber);
    };

    $scope.calculateProduct = function () {
        if (typeof $scope.firstNumber !== 'number' ||
            !isFinite($scope.firstNumber) ||
            typeof $scope.secondNumber !== 'number' ||
            !isFinite($scope.secondNumber)) {
            $scope.productResult = 'Enter both numbers.';
            return;
        }

        $scope.productResult =
            multiplicationService.multiply(
                $scope.firstNumber,
                $scope.secondNumber
            );
    };
}

})();

The $inject array explicitly lists the controller’s dependencies. This annotation keeps dependency names available if a JavaScript minifier shortens function parameter names. An alternative is AngularJS array-style annotation, such as ['$scope', 'squareService', function (...) { ... }].

4. Understand how the two services are called

When AngularJS creates myController, it supplies the requested $scope, squareService and multiplicationService dependencies. The controller then calls the methods exposed by those services:

  • squareService.square(5) returns 25.
  • multiplicationService.multiply(4, 6) returns 24.

The controller handles the page interaction, while the services contain the reusable calculation logic. If another controller needs the same calculation, it can inject the same service rather than copying the method.

AngularJS Service Example
Original output screenshot retained from the earlier tutorial.

5. Understand the difference between service and factory

AngularJS provides more than one way to register reusable dependencies. Two commonly used methods are .service() and .factory():

  • .service(): register a constructor function. AngularJS instantiates it and makes the resulting object injectable.
  • .factory(): register a factory function. The value returned by that function becomes the injectable service.

For example, a factory can return an object containing the same calculation method:

angular.module('calculator.services')
    .factory('squareFactory', function () {
        return {
            square: function (number) {
                return number * number;
            }
        };
    });

Choose the registration style that fits the object you want to provide. Both approaches use AngularJS dependency injection; they differ in how the injectable value is created.

Common mistakes to check

  • Module dependency missing: make sure mainApp includes calculator.services in its dependency array.
  • Name mismatch: the service name in .service() must match the name injected into the controller. AngularJS dependency names are case-sensitive.
  • Wrong script order: load AngularJS before app.js.
  • Module recreated accidentally: use angular.module('mainApp', []) to create a module. Use angular.module('mainApp') without the second argument when retrieving an existing module; passing a new dependency array creates or replaces the module definition.
  • Minification breaks injection: use $inject or array annotation for functions that receive dependencies.
  • Empty or invalid input: check the input model before performing a calculation, as the example does.

Frequently asked questions

Are AngularJS services singletons?

AngularJS services are instantiated lazily and behave as singletons within an injector. Components using the same registered service through that injector receive the same instance.

Can one AngularJS service be injected into another service?

Yes. A service constructor or factory can request other registered services through dependency injection. This is useful when one reusable component depends on another.

What is the difference between AngularJS and Angular?

AngularJS refers to the older 1.x framework. Modern Angular is a separate framework with a different architecture and APIs. Do not assume that AngularJS examples can be copied directly into a modern Angular application.

Should I use AngularJS for a new project?

No. Official AngularJS support ended in January 2022, and the project repository is archived. For a new application, evaluate a currently supported framework. If you maintain a legacy AngularJS application, review its security exposure and plan an appropriate migration or supported-maintenance strategy.

Why use the $inject annotation?

The annotation explicitly records dependency names so AngularJS can resolve them even if a build process minifies or renames the controller’s function parameters.

Conclusion

AngularJS services provide a simple way to separate reusable logic from controllers. In this example, squareService and multiplicationService are registered in a service module and injected into one controller through the main application module. The same pattern can be used to organise shared logic in an existing AngularJS codebase.

Because AngularJS is no longer officially supported, treat this as a legacy maintenance example. For new development, refer to the documentation for the actively supported Angular framework.

References and further reading

RochakGuy

Hi, I'm Piyush and I'm a passionate blogger. I love sharing my insights on Rochaksite.com. I'm committed to providing practical and informative content that helps readers achieve their goals and make informed decisions. When I'm not writing, I enjoy exploring new topics and trends in Technology and indulging in my personal hobbies and interests.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button