0

The below code contains 2 views and I want to get the data from index to user.

JS code:

var app=angular.module("myApp",[]);

app.controller("MainController",function($scope,$window,$rootScope)
{
    $rootScope.loc={UserName:"",Pwd:""};
    $scope.name="";
    $scope.check=function()
    {
        $scope.name=$rootScope.loc.UserName;

        if(($rootScope.loc.UserName !="") && ($rootScope.loc.Pwd!=""))
        {
            alert($scope.name);
            $window.location = 'user.html'
        }
    }
});

main.html

Name: <input type="text" ng-model="loc.UserName">
Pwd: <input type="text" ng-model="loc.Pwd">
<br><br>
<input type="submit" id="submit" value="Award me" ng-click="check()">

user.html

<h1 id="honor" ng-controller="MainController">{{name}}!!!!</h1>
georgeawg
  • 48,608
  • 13
  • 72
  • 95
  • You can add your data in `$rootScope` and then use it in your application but using `$rootScope` is not advised, you should either use `controllerAs` or make use of a `service` – Aayushi Jain Aug 01 '17 at 04:04

2 Answers2

1

Using $rootScope is not recommended, you can make use of angular service to do the same.

Create a service, that will hold model variables.

angular.service("dataService", function() {
    this.value1 = "";  
});

Then you can reference that service in your controllers,

angular.controller("myCntrl1", function($scope, dataService) {
    $scope.dataService = dataService;
});


angular.controller("myCntrl2", function($scope, dataService) {
    $scope.dataService = dataService;
});
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
1

We can create a service to set and get the data between the controllers and then inject that service in the controller function where we want to use it.

Service :

app.service('setGetData', function() {
  var data = '';
    getData: function() { return data; },
    setData: function(requestData) { data = requestData; }
});

Controllers :

app.controller('myCtrl1', ['setGetData',function(setGetData) {

  // To set the data from the one controller
  var data = 'Hello World !!';  
  setGetData.setData(data);

}]);

app.controller('myCtrl2', ['setGetData',function(setGetData) {

  // To get the data from the another controller  
  var res = setGetData.getData();
  console.log(res); // Hello World !!

}]);

Here, we can see that myCtrl1 is used for setting the data and myCtrl2 is used for getting the data. So, we can share the data from one controller to another controller like this.

Debug Diva
  • 26,058
  • 13
  • 70
  • 123