Friday 11 May 2018

Passing data between controllers using $state.go() in AngularJS


In this article, I would like you to know about passing data between controllers using $state.go(). There are mainly 3 methods are there to pass data through $state.go().
1.         Without using url : i.e., by using params should declare at provider state is configuring
2.       using url : i.e., the passing data is displayed in url after slash ‘/’
3.       using querystring : i.e., the data is passed as query string , that can be seen in url.
I had taken 4 js controllers and 4 html view templates and one index.html and one app.js file.
In app.js I had created a module and injected ui.router to route the html pages and to change the state of the Single Page Application using $stateProvider.

After creating the module, configure the module with Providers. i.e., $stateprovider, $urlRouteProvider, $locationProvider, And declare and define the states of the routing controllers and views and urls and state names.
The below code in app.js shows the creating module and configuring the module in AngularJS
app.js
var angpp = angular.module("AngularPassDataBetweenControllersApp", ['ui.router']);
angpp.config(function ($stateProvider, $urlRouterProvider, $locationProvider) {
    // $locationProvider.hashPrefix('!');//To Add ! After # from URL
    // $locationProvider.html5Mode(true); //To Remove # from URL
    $urlRouterProvider.otherwise("/home");

    $stateProvider

    var homeState = {
        name: 'home',
        url: '/home',
        templateUrl: 'Views/home.html',
        controller: 'HomeController'
    }
    $stateProvider.state(homeState);

    var contentState = {
        name: 'content',
        url: '/content',
        params: { ItemCode: null, ItemName: null, ItemPrice: null },
        templateUrl: 'Views/content.html',
        controller: 'ContentController'
    }
    $stateProvider.state(contentState);

    var resourceState = {
        name: 'resource',
        url: '/resource/:ItemCode/:ItemName/:ItemPrice',
        templateUrl: 'Views/resource.html',
        controller: 'ResourceController'
    }
    $stateProvider.state(resourceState);

    var stockState = {
        name: 'stock',
        url: '/stock?ItemCode&ItemName&ItemPrice',
        templateUrl: 'Views/stock.html',
        controller: 'StockController'
    }
    $stateProvider.state(stockState);

})

Now design the html with home, content, resource and stock menus as follows in index.html as it is the main view and encapsulate the html with ng-app with the module name :

By using the old version 0.2.8 angular-ui-router.min.js, then it shows the following error, can be seen at inspect or by pressing F12.

Uncaught Error: [$injector:modulerr] Failed to instantiate module AngularPassDataBetweenControllersApp due to: Error: Invalid params in state 'content'

To rectify this error, I used latest version of  angular-ui-router.min.js, i.e., 0.4.2. Then it works fine and the code we had to write in index.html is as follows :

index.html

<!DOCTYPE html>
<html>
<head>

    <!-- The Below CSS Is To Load Bootstrap -->
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
    <style>
        .navbar {
            border-radius: 0;
        }
    </style>

    <!-- The Below JS Is For Anuglar -->
    <script src="http://code.angularjs.org/1.2.13/angular.js"></script>
    <!-- The Below JS Is For ui-router -->
    <!--<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js"></script>-->
   <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js"></script>
    <!-- The Below app.js File Is To Define The Angular Application And Routings -->
    <script src="app.js"></script>
    <!-- The Below js Files Are The Content That We Inject In Single Page Application -->
    <script src="Controllers/home.js"></script>
    <script src="Controllers/content.js"></script>
    <script src="Controllers/resource.js"></script>
    <script src="Controllers/stock.js"></script>
</head>

<!-- Applying Root Element Of AngularJS To HTML Body -->
<body ng-app="AngularPassDataBetweenControllersApp">

    <!-- Navigation Menubar -->
    <nav class="navbar navbar-inverse" role="navigation">
        <ul class="nav navbar-nav">
            <li><a ui-sref="home">Home</a></li>
            <li><a ui-sref="content">Content</a></li>
            <li><a ui-sref="resource">Resource</a></li>
        </ul>
    </nav>

    <!-- Main Content -->
    <div class="container">

        <!-- The Content Will Inject Here -->
        <div ui-view></div>

    </div>

</body>
</html>

The above code displays the menus and initializes the ng-app and now I am taking two folders named controllers and views where I want to take js controllers and html views respectively in that folders. From Home controller I wanna pass data to the other controllers using $state.go() and the methods of passing data through $state.go() is in 3 different manners that we had discussed previously i.e., without url using params, using url with slash ‘/’ and using querystring format.

Now the home.js is coded as below :

home.js

angpp.controller('HomeController', function ($scope, $window,$state) {
   
    $scope.PassDataToContent = function () {
        // here i wanna pass data to content named state through $state.go() method
        $state.go('content', { ItemCode: $scope.ItemCode, ItemName: $scope.ItemName, ItemPrice: $scope.ItemPrice });
    }

    $scope.PassDataToResource = function () {
        // here i wanna pass data to resource named state through $state.go() method
        $state.go('resource', { ItemCode: $scope.ItemCode, ItemName: $scope.ItemName, ItemPrice: $scope.ItemPrice });
    }

    $scope.PassDataToStock = function () {
        // here i wanna pass data to stock named state through $state.go() method
        $state.go('stock', { 'ItemCode': $scope.ItemCode, 'ItemName': $scope.ItemName, 'ItemPrice': $scope.ItemPrice });
    }

   
});

home.html

<div class="col-md-6 col-sm-6 container">
    <div class="row">
        <h3>AngularJS - Passing Data Between Controllers Using $state.go()</h3>
    </div>
    <form class="form-horizontal col-md-6 col-sm-6">
        <div class="form-group col-md-12 col-sm-12">
            <label>Item Code</label>
            <input type="text" name="itemcode" class="form-control" id="itemcode" ng-model="ItemCode" />
        </div>
        <div class="form-group col-md-12 col-sm-12">
            <label>Item Name</label>
            <input type="text" name="itemname" class="form-control" id="itemname" ng-model="ItemName" />
        </div>
        <div class="form-group col-md-12 col-sm-12">
            <label>Item Price</label>
            <input type="text" name="itemprice" class="form-control" id="itemprice" ng-model="ItemPrice" />
        </div>
     
        <div class="form-group col-md-12 col-sm-12">
            <button type="button" name="search" class="btn btn-primary" id="search" ng-click="PassDataToContent()">Pass Data To Content</button>
            </div>
        <div class="form-group col-md-12 col-sm-12">
            <button type="button" name="clear" class="btn btn-danger" id="clear" ng-click="PassDataToResource()">Pass Data To Resource</button>
            </div>
        <div class="form-group col-md-12 col-sm-12">
            <button type="button" name="clear" class="btn btn-success" id="clear" ng-click="PassDataToStock()">Pass Data To Stock</button>
        </div>

</form>
</div>

The design of the home.html page looks as below :


Here to receive the data from HomeController to other controller, we have to use $stateParams, we have to implement another controller named ContentController and View as follows :

The code to without displaying the data in the url is as follows :

content.js

angpp.controller('ContentController', function ($scope, $window,$state,$stateParams) {
  
    $scope.ItemCode = $stateParams.ItemCode;
    $scope.ItemName = $stateParams.ItemName;
    $scope.ItemPrice = $stateParams.ItemPrice;

    $scope.BackToHome = function () {
        $state.go('home');
    }
   
});

content.html

<div class="form-group container">
    <div class="row">
        <h3>Content</h3>
    </div>
    <div class="form-horizontal col-md-6 col-sm-6">
        <div class="col-md-12">
            <label>Item Code :</label>
            {{ItemCode}}
        </div>
        <div class="col-md-12">
            <label>Item Name :</label>
            {{ItemName}}
        </div>
        <div class="col-md-12">
            <label>Item Price :</label>
            {{ItemPrice}}
        </div>

    </div>
    <div class="col-md-12">
        <button type="button" name="search" class="btn btn-primary" id="search" ng-click="BackToHome()">Back To Home</button>
    </div>
</div>

Now Enter the data in the input controls of Home view and click on ‘Pass Data To Content’ button, then it shows as below without showing any data in the url :




Now you will get the content page / view with data displayed in it and no data is shown in URL as below :



Now click on ‘Back To Home’ button it comes to the Home view.

Here to receive the data from HomeController to other controller, we have to use $stateParams, we have to implement another controller named ResourceController and View as follows :

The code to display the data in the url after slash (/) is as follows :

resource.js
angpp.controller('ResourceController',['$scope', '$window','$state','$stateParams', function ($scope, $window,$state,$stateParams) {
   
    $scope.ItemCode = $stateParams.ItemCode;
    $scope.ItemName = $stateParams.ItemName;
    $scope.ItemPrice = $stateParams.ItemPrice;

    $scope.BackToHome = function () {
        $state.go('home');
    }
}]);

resource.html

<div class="form-group container">
    <div class="row">
        <h3>Resource</h3>
    </div>
    <div class="form-horizontal col-md-6 col-sm-6">
        <div class="col-md-12">
            <label>Item Code :</label>
            {{ItemCode}}
        </div>
        <div class="col-md-12">
            <label>Item Name :</label>
            {{ItemName}}
        </div>
        <div class="col-md-12">
            <label>Item Price :</label>
            {{ItemPrice}}
        </div>

</div>
    <div class="col-md-12">
    <button type="button" name="search" class="btn btn-primary" id="search" ng-click="BackToHome()">Back To Home</button>
        </div>
</div>

Now enter the data in the input controls of Home view and click on ‘Pass Data To Resource’ button, then it shows as below showing data in the url after slash(/) :


Now you will get the resource page / view with data displayed in it and  data is displayed in URL after slash(/) as below :



Now click on ‘Back To Home’ button it comes to the Home view.

Here to receive the data from HomeController to other controller, we have to use $stateParams, we have to implement another controller named StockController and View as follows :

The code to display the data in the  as query string is as follows :

stock.js

angpp.controller('StockController', ['$scope', '$window', '$state', '$stateParams', function ($scope, $window, $state, $stateParams) {

    $scope.ItemCode = $stateParams.ItemCode;
    $scope.ItemName = $stateParams.ItemName;
    $scope.ItemPrice = $stateParams.ItemPrice;

    $scope.BackToHome = function () {
        $state.go('home');
    }
}]);

stock.html

<div class="form-group container">
    <div class="row">
        <h3>Stock</h3>
    </div>
    <div class="form-horizontal col-md-6 col-sm-6">
        <div class="col-md-12">
            <label>Item Code :</label>
            {{ItemCode}}
        </div>
        <div class="col-md-12">
            <label>Item Name :</label>
            {{ItemName}}
        </div>
        <div class="col-md-12">
            <label>Item Price :</label>
            {{ItemPrice}}
        </div>

    </div>
    <div class="col-md-12">
        <button type="button" name="search" class="btn btn-primary" id="search" ng-click="BackToHome()">Back To Home</button>
    </div>
</div>

Now enter the data in the input controls of Home view and click on ‘Pass Data To Stock’ button, then it shows as below showing data in the url  as query string :


Now you will get the stock page / view with data displayed in it and  data is displayed in URL as a query string as below :


No comments:

Post a Comment

Note: only a member of this blog may post a comment.