Sunday, August 17, 2014

Consume service of AngularJS within Controller

The advantage of the service in AngularJS is it is singleton in nature,  so it perform great role when we want to share data across controller.  We can create any number of services and attach with module and then we can able to access those services from any page.

Generally concept of service gives 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 controller, as we said service is singleton ,so that it always can able to keep track on 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.

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, just we are 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 controller and inject the dataService within it, so that we can able to consume dataService within controller.
Here is the implementation of fistController which contains getdata method and it will return the latest collection from service after populating initial data in service.



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 fom service.

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 have done with AngularJS part, now we have to implement html client to execute the controller.  Here is the sample code.
<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.

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

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.


Conclusion:-
In this example we have learned to consume service in controller of AngularJS. It’s 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.




No comments:

Post a Comment