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>
1
  • 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 Commented Aug 1, 2017 at 4:04

2 Answers 2

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Downvoter write down the reason
Where will the check() function go ? In the service or controller 1 ?
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.