0

I am writing an app with angularjs and I don't know how to access the variables in my main-controller.

gsg_main.controller('mainCtrl',['$scope','SessionService','$http','$routeParams','MessageService','$interval','$location','orderByFilter',function($scope,SessionService,$http,$routeParams,MessageService,$interval,$location,orderBy){
//variablen
var self = this;
self.username = "any_name";

I want to access username from a nested controller:

gsg_main.controller('testCtrl',['$scope',function($scope){
var self = this;
self.testvar = $scope.$parent.username;

}]);

I also tried:

self.testvar = $scope.$parent.parent.username;

which I found in other posts.

Is there a way without using $scope in the main-controller?

Thanks for your help.

1
  • 2
    You could always use a service to share values between controllers. Commented Nov 30, 2016 at 15:20

1 Answer 1

1

Create a service:

  .service('UsernameService', function() {
    var username = null;

    this.setUsername = function(value) {
      username = value;
    };

    this.getUsername = function() {
      return username;
    }
  })

Inject it into your controllers:

  .controller('mainCtrl', ['$scope', 'UsernameService', function($scope, UsernameService) { ... }

Then you can call these functions to get and set the username value:

 UsernameService.setUsername("any_name");
 ...
 self.testvar = UsernameService.getUsername();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.