posted by  on  

If we are using Views in our application and want to pass the data from one controller to another controller just follow given simple steps.

Here we have Single Page Application(SPA) in which if we want to pass data for that this example is given:

"Index.html"

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h3>
      Share data from one conroller to another using $routeScope
    </h3>
    <div ng-view=""></div>
</body>

<script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
<script data-require="angular-route@*" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular-route.js"></script>
<script src="routeApp.js"></script>
<script src="app.js"></script>

</html>

"View1.html"

Whatever we will write in textbox it will be shown in "View2.html" textbox.

<div>
  <label>Text : </label>
  <input type="text" name="fname" value="AbcdXyz" ng-model="fname" />
  <a href="" ng-click="shareData()">Link</a>
</div>

"View2.html"

<div>
  <label>Data :</label>
  <input type="text" name="fname" value="" ng-model="fname" readonly />
  <a href="index.html#/" ng-click="shareData()">Back</a>
</div>

"routeApp.js"

This file is for routing to achieve SPA.

var myApp = angular.module('myApp', ['ngRoute', 'yourApp']);
myApp.config(['$routeProvider', function ($routeProvider) {

$routeProvider
  .when('/',
  {
    templateUrl: 'View1.html',
    controller: 'View1'
  }).
  when('/View2',
  {
    templateUrl: 'View2.html',
    controller: 'View2'
  }).
  otherwise(
  {
    redirectTo: '/'
  });
}]);

"app.js"

Here we are using $rootScope for sharing Data.

var yourApp = angular.module("yourApp",[]);
yourApp.controller("View1", function ($rootScope, $scope, $window) {

$rootScope.abc = $scope.fname;

$scope.shareData = function () {

    $rootScope.abc = $scope.fname;
    $window.location.href = "#/View2";
  }
});

yourApp.controller("View2", function ($rootScope, $scope, $window) {
  $scope.fname = $rootScope.abc;
});

If you want to view the code Click HERE.

Lateshtclick Technology Blog
Tags AngularJS
posted by Latesht Click Latesht Click

Comments


Leave a Reply

Feel free to contribute!
Comment:
Name*:
Email*: