ashishkumar148
ashishkumar148

Reputation: 1005

Data passing between angularjs pages

I am working on an application which uses angularjs. In this i have a login page which lead up to home page. Login page is managed by loginCtrl which is further using loginService.

this is loginctrl (Login Controller)

'use strict';
angular.module('dreamflow').controller('LoginCtrl', ['$scope', 'LoginService',
function($scope, LoginService) {
    $scope.title = "Login";
    $scope.master = {}

    $scope.login = function() {
        var user = {
            username: $scope.username,
            password: $scope.password
        };
        LoginService(user);
    };

}
]);

this is loginService

angular.module('dreamflow')
.factory('LoginService', function($http, $location, $rootScope) {
    return function(user) {
        $http.post('/login',{
                username: user.username,
                password: user.password
            }).then(function(response) {
            if (response.data.success) {
                console.log(response.data);
                $rootScope.user = response.data.user;
                $location.url('/');
            } else {
                console.log(response.data.errorMessage);
                $location.url('/');
            }
        });
    };
});

In the above code user details is coming after checking the success of response and then we are redirected to the home page. I want to access the user details coming in $rootScope.user in home page angular controller.

Upvotes: 0

Views: 847

Answers (1)

penguinsource
penguinsource

Reputation: 1190

You can have a service which will hold the login username and the service will injected into both controllers as such:

jsfiddle with '$scope'

Also, I find that using 'this' instead of '$scope' is helpful in not mixing up controller scopes between each other in case you use more than one controller in the same place. There are also other reasons.

HTML:

<div ng-app="myApp">

    <div  ng-controller="ControllerOne as one">
        <h2>ControllerOne:</h2>
        Change testService.loginName: <input type='text' ng-model='one.myService.loginName'/> </br></br>
        myName: {{one.myService.loginName}}
    </div>
    <hr>
    <div ng-controller="ControllerTwo as two">
        <h2>ControllerTwo:</h2>
        myName: {{two.myService.loginName}}
    </div>

</div>

JS:

app.service('testService', function(){
    this.loginName = "abcd";
});

app.controller('ControllerOne', function($scope, testService){
    this.myService = testService;
});

app.controller('ControllerTwo', function($scope, testService){
    this.myService = testService;
});

jsfiddle with 'this'

Upvotes: 1

Related Questions