Blogger news

Blogger templates

Tuesday, August 26, 2014

Sharing data between controllers in AngularJS

If you are new to AngularJS I would prefer to go through my introduction blog on AngularJS before read this article.

Data and State are foundation of our application. A good developer will always think about brilliant way to handle both. When you go through AngularJS documentation these two items generally store in controllers and this works fine if you are working in a very small application. As your application grows it may be difficult to handle. Re usability should be one of basic qualities of a developer. When follow MVC architecture 'M' stands for model and model encapsulates your data or I would say model is the logical representation of your physical data objects. If you are familiar with C# you may know POCO to represent data   which is equivalent to POJO Java and sharing those objects to different classes is very easy. Here I will demonstrate how share data (Nothing but model) to different controllers in AngularJS and which we will achieve through services. 

Let's think about a scenario where we have an application to maintain Cars which  a home page and a controller say home controller and I want to share data between two other controllers say SaveController and EditController. I will show how we achieve that with service. 


My home controller will looks like below,
app.controller('HomeController'function ($scope, $location, CarMakingFactory,CarModelService) {

    $scope.Cars = CarMakingFactory.GetAllCars();

    $scope.Edit = function (car) {
        CarModelService.Car = car;
        $location.url("/EditCar");
    };


    $scope.CreateNewCar = function () {
        $location.url('/NewCar');
    };

});

Where you look at this controller you can see we are injecting four components, $scope, $location,CarMakingFactory and CarModelService. I know you will defenitely know what $scope is else read my blog on Introduction to AngularJS before proceed with this article. $location service using for routingCarMakingFactory is a factorymethod and CarModel service is the component we are really interested in and I will explain that soon. Also you can see two methods in controller edit and CreateNewCar and both of that routing to corresponding view using $location service. Code to route is below,

var app = angular.module('app', ['ngRoute'])
    .config(function ($routeProvider) {
        $routeProvider.when('/NewCar', {
            templateUrl: '../Views/Partials/NewCar.html',
            controller: 'NewCarController'
        }).when('/EditCar', {
            templateUrl: '../Views/Partials/EditCar.html',
            controller: 'EditCarController'
        }).otherwise();


    });

We will have two controllers for EditCar and NewCar views and that is where we are going to share data. 
Let's create car model

app.service('CarModelService'function () {
    this.Car = { CarName: '', Model: '', Color: '' }
})
So we created a model for Car..look at the highlighted area. This is the common place of the model for our other two controllers which I will explain soon. Let's create NewCarController,
app.controller("NewCarController"function ($scope, CarModelService) {

    $scope.car = CarModelService.Car;
});

and NewCar.html (Which is a partial view)
<div>

    <table>
        <tr>
            <td>Car Name:</td>
            <td><input type="text" ng-model="car.CarName" />{{car.CarName}}</td>
        </tr>
        <tr>
            <td>Car Model:</td>
            <td><input type="text" ng-model="car.Model" /></td>
        </tr>
        <tr>
            <td>Car Color:</td>
            <td><input type="text" ng-model="car.Color" /></td>
        </tr>
        <tr>
            <td>Save:</td>
            <td><input type="button" value="Save" ng-click="Save(car)" /></td>
        </tr>
    </table>
</div>

When you look at the view ng-model is binded to car object that we got from CarModelService. Next I will show EditCarController,
app.controller("EditCarController"function ($scope, CarModelService) {

    $scope.car = CarModelService.Car;

});

You can see EditCarController also sharing same Car object from CarModelService. EditCar.html is below,
<div>

  <table>
     <tr>
         <td>Car Name:</td>
         <td><input type="text" ng-model="car.CarName" />{{car.CarName}}</td>
      </tr>
      <tr>
        <td>Car Model:</td>
         <td><input type="text" ng-model="car.Model" /></td>
      </tr>
      <tr>
         <td>Car Color:</td>
         <td><input type="text" ng-model="car.Color" /></td>
      </tr>
      <tr>
         <td>Save:</td>
         <td><input type="button" value="Edit" ng-click="Edit(car)" /></td>
      </tr>
  </table>
</div>

If you look at Edit function in "HomeController" you can see we are setting Car object of CarModelService like below,CarModelService.Car = car;
Where 'car' object will contain data to be edited. Now I will show CarHome.html so that you will get a picture how we are passing 'car' object to Edit method,
<!DOCTYPE html>
<html ng-app="app">
<head lang="en">
    <meta charset="UTF-8">
    <title></title>

</head>
<body ng-controller="HomeController">
    <div>
        <table>
            <tr>
                <th>Car Name</th>
                <th>Model</th>
                <th>Color</th>
            </tr>



            <tr ng-repeat='car in Cars'>
                <td>
                    <h3>{{car.CarName}}</h3>
                </td>
                <td>
                    <h3>{{car.Model}}</h3>
                </td>
                <td>
                    <h3>{{car.Color}}</h3>
                </td>
                <td>
          <input type="button" value="Edit" ng-click="edit(car)" />
                </td>
            </tr>
            <tr>
                <td>
          <input type="button" value="CreateNewCar" ng-click="CreateNewCar()" />
                </td>
            </tr>
        </table>




    </div>

    <ng-view></ng-view>

    <script type="text/javascript" src="../AngularScripts/Angular.min.js"></script>
    <script type="text/javascript" src="../AngularScripts/angular-route.min.js"></script>
    <script type="text/javascript" src="../Modules/app.js"></script>
    <script type="text/javascript" src="../Controllers/HomeController.js"></script>
    <script type="text/javascript" src="../Factories/CarMakeFactory.js"></script>
    <script type="text/javascript" src="../Services/CarModelService.js"></script>
    <script type="text/javascript" src="../Controllers/NewCarController.js"></script>
    <script type="text/javascript" src="../Controllers/EditCarController.js"></script>

</body>
</html>

That's it, your data is now sharing between two controllers.
You can download full code here

No comments:

Post a Comment