How to use variables from a controller in another

2019-09-16 17:17发布

问题:

I'm new in AngularJS and I want to use the username and password variables that I get in this controller:

.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state, Api) {
    $scope.data = {};

    $scope.login = function() {

        LoginService.loginUser($scope.data.username, $scope.data.password)
        .success(function(data) {
            $scope.data = {}
            $state.go('tabs.extranet');
        })
        .error(function(data) {
            var alertPopup = $ionicPopup.alert({
                title: 'Acceso denegado',
                template: 'Por favor, compruebe su usuario y/o contraseña'
            });
            $state.go('tabs.extranet');
        });
    };
})

Inside this controller

.controller('SaesoTabCtrl', function($scope, $sce, Saeso, Api){
    //some code....
}

Thanks

回答1:

Use a model-type value or your LoginService and inject it into both controllers. Save the data onto the service rather than the controller.

model

ngModule.value( 'session', { username:'', sessionId: '' });

session service

ngModule.service( 'sessionService', function(){
    var api = { username: '', sessionId: '' }
    api.doLogin = function(){}

    return api;
})

injection into controllers

ngModule.controller( 'LoginCtrl', function( $scope, session<Service> ){

     $scope.doLogin = function( un, pw ){
          sessionService.doLogin( un, pw )
          .then( function( rsp ){
               sessionService.username = un
               sessionService.sessionId = rsp
          })
     }
})
ngModule.controller( 'SaesoTabCtrl', function( session<Service> ){ ... })

note - I do not recommend that you store your password data in either of these solutions, this was simply to further illustrate the point. Hopefully your login service provides a session id that expires after a certain time.



回答2:

You can add vars to $rootScope and access them in any controller using $rootScope.varname.

This is not good practice because its essentially similar to introducing global Angular variables.

A better approach, which may or may not work in your situation, is to define two controllers as follows:

<body ng-controller="MainController">

  <!-- only MainController is accessible here -->
  <div ng-controller="InnerController">

    <!-- both MainController and InnerController are accessible here -->
    <!-- main controllers $scope variables should also be accessible in InnerController -->

  </div>

</body>

I would be interested if you try the latter approach to know if you got it working. This demonstrates scopical inheritance. Maybe you can make a plunker for this?



回答3:

Try to put your data inside the $rootScope. It is accessible from anywhere in the application.