Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / Javascript
Tip/Trick

Consume Service of AngularJS Within Controller

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
18 Aug 2014CPOL2 min read 8.5K   2  
In this tip, we will learn to share data from service to controller in AngularJS

Introduction

The advantage of the service in AngularJS is that it is singleton in nature, so it performs a great role when we want to share data across controller. We can create any number of services and attach with module and then we will be able to access those services from any page. Generally, the concept of service gives the idea of re-usability. For example, if I have one common database operation in many pages of application, then I can create one service and I will consume the service from various controllers, as we said service is singleton, so that it will always be able to keep track of the latest data. So, let’s create one simple service and we will consume the service in two different controllers. Here is the code for data service.

JavaScript
var app = angular.module('myApp', []);
app.service('dataService', function () {
    var person = [];

    var populateData = function () {
        person.push({ name: 'souav', surname: 'kayal' });
        person.push({ name: 'foo', surname: 'bar' });
    }
    var returnData = function(){
        return person;
    }
    var pushData = function(data){
        person.push(data);
    }

    return { 
        returnData: returnData ,
        populateData : populateData,
        pushData : pushData
    };
});

The implementation is very simple, we are just populating person object within populateData function and pushData function will add one more object in collection. The returnData function will return the latest collection to caller. Now, let’s create a controller and inject the dataService within it, so that we will be able to consume dataService within controller. Here is the implementation of firstController which contains getdata method and it will return the latest collection from service after populating initial data in service.

JavaScript
app.controller('firstController', function ($scope, dataService) {

        $scope.getdata = function () {
            dataService.populateData();
            var returnData = dataService.returnData();
            alert(JSON.stringify(returnData));
        }
});

Now, we will implement the second controller which will contain pushData function to add another new data to collection which we are maintaining in service and newData function which will pull the latest data from service.

JavaScript
app.controller('secondController', function ($scope, dataService) {
    $scope.pushData = function () {
        dataService.pushData({ name: 'ram', surname: 'kumar' });
    }

    $scope.newData = function () {
        var data = dataService.returnData();
        alert(JSON.stringify(data));
    }
});

Ok, we are done with the AngularJS part, now we have to implement HTML client to execute the controller. Here is the sample code.

HTML
<body>
        <div ng-controller="firstController">
            <input type="button" name="gatdata" value="Get Initial Data" ng-click="getdata()" />
        </div>
        <div ng-controller="secondController">
            <input type="button" name="pushdata" value="Add Data" ng-click="pushData()" />
            <input type="button" name="gatdata" value="Get latest data" ng-click="newData()" />
        </div>
    </body>

This is the view of HTML page.

Image 1

Once we click on Get initial Data button, we should see the below screen, it’s loading data from service initially.

Image 2

The press Add Data button and then press Get latest Data button and we will see the below screen. We are seeing that one more object has added to person object which we are maintaining in service.

Image 3

Conclusion

In this example, we have learned to consume service in controller of AngularJS. It’s a good approach to implement service per functionality and consume it to controller. For example, we can implement login service and consume it in login controller.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer DELL International
India India
I am software developer from INDIA. Beside my day to day development work, i like to learn new technologies to update myself. I am passionate blogger and author in various technical community including dotnetfunda.com , c-sharpcorner.com and codeproject. My area of interest is modern web technology in Microsoft stack. Visit to my personal blog here.

http://ctrlcvprogrammer.blogspot.in/

Comments and Discussions

 
-- There are no messages in this forum --