4

I have some issue with AngularJS scope and location. Here is an example :

function CreateAccountCtrl($scope, $http, $location) {
    ...
    $http.post(url,$scope.form).
        success(function(data){
            $location.path('/'); // I need to transfert data to the location 
        }
}

My problem is : I want to transfer the data to the / controller, I thought to use the rootScope but I don't think it is the best way to do this.

Any idea ?

1
  • 1
    To pass data between controllers you can create a shared service that is injected in both controllers, or if the data is not complex just call / with some parameters and then access them using $routeParams. Commented Dec 6, 2012 at 19:20

2 Answers 2

6

You can use $rootScope to send data between controllers. $routeParams doesn't allow send complex data structures. Let's see it.

Assign returned data of success callback to variable in $rootScope. Navigate to the AccountController.

function CreateAccountCtrl($scope, $http, $location,$rootScope ) {
    ...
    $http.post(url,$scope.form).
        success(function(data){
            $rootScope.accountInfo = data; 
            $location.path('/account');
        }
}

Configure the route in the $routeProvider:

$routeProvider.when('/account', {
    template: 'account.html',
    controller: AccountCntl  
});

In the AccountController can access the data on $rootScope.

function AccountCtrl($scope, $rootScope) {
    $scope.accountInfo = $rootScope.accountInfo;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think this is the best method so far to achieve this. the only problem would be if a different controller loaded with the wrong model on rootscope.
1

Use the $routeParams service.

function CreateAccountCtrl($scope, $http, $location) {
    ...
    $http.post(url,$scope.form).
        success(function(data){
            $location.path('/account/' + data.accountId);
        }
}

Configure the route in the $routeProvider:

$routeProvider.when('/account/:accountId', {
    template: 'account.html',
    controller: AccountCntl  
});

Your AccountController can now access the data:

function AccountCtrl($scope, $routeParams) {
    $scope.accountId = $routeParams.accountId;
}

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.