angularjs 页之间的数据传递

Data passing between angularjs pages

我正在开发一个使用 angularjs 的应用程序。在此我有一个登录页面,该页面通向主页。登录页面由 loginCtrl 管理,后者进一步使用 loginService.

这是 loginctrl(登录控制器)

'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);
    };

}
]);

这是登录服务

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('/');
            }
        });
    };
});

在上面的代码中,用户详细信息在检查响应成功后出现,然后我们被重定向到主页。我想访问主页 angular 控制器中 $rootScope.user 中的用户详细信息。

你可以拥有一个保存登录用户名的服务,该服务将像这样注入到两个控制器中:

jsfiddle with '$scope'

此外,我发现使用 'this' 而不是 '$scope' 有助于避免混淆彼此之间的控制器范围,以防您在同一个地方使用多个控制器。还有其他原因。

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'