2016-11-30 7 views
0

私はangularjsのアプリを書いていますが、私はメインコントローラの変数にアクセスする方法がわかりません。

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"; 

私はネストされたコントローラからユーザ名をアクセスしたい:

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

}])。

私も試してみました:

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

私は他の記事で見ました。

メインコントローラで$ scopeを使用しない方法はありますか?

ありがとうございました。

+2

あなたができました常にサービス間で値を共有するサービスを使用します。 – Lex

答えて

1

サービスを作成します。

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

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

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

は、あなたのコントローラにそれを注入:

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

その後、ユーザー名の値を取得および設定するためにこれらの関数を呼び出すことができます。

UsernameService.setUsername("any_name"); 
... 
self.testvar = UsernameService.getUsername(); 
+0

ありがとうございました。 – Tobi

関連する問題