AngularJS Services How to use a service

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

    angular.module("app")
        
        // Custom services are injected just like Angular's built-in services
        .controller("step1Controller", ['counterService', '$scope', function(counterService, $scope) {
            counterService.number++;
            // bind to object (by reference), not to value, for automatic sync
            $scope.counter = counterService;
        })

In the template using this controller you'd then write:

// editable
<input ng-model="counter.number" />

or

// read-only
<span ng-bind="counter.number"></span>

Of course, in real code you would interact with the service using methods on the controller, which in turn delegate to the service. The example above simply increments the counter value each time the controller is used in a template.


Services in Angularjs are singletons:

Services are singleton objects that are instantiated only once per app (by the $injector) and lazy loaded (created only when necessary).

A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to said instance. As stated here



Got any AngularJS Question?