如何在AngularJS中跨页面共享数据

时间:2014-05-27 12:34:24

标签: javascript angularjs

我有两页。一个是login.html,第二个是home.html。登录成功后,会重定向到home.html。我想在home.html中访问用户的ID 所以我从名为" loginForm"的控制器中保存了id。 (login.html的控制器)setCurrentUser(id)中的services.js 并尝试从名为" expenseForm"的控制器访问id。 (home.html的相应控制器)到getCurrentUser()。但它是空字符串。请指导我。

controller.js -

var expmodule = angular.module('myApp.controllers', []);

expmodule.controller('loginForm', function($scope, sharedProperties) {
    $scope.login = function (userid, password) {
        var users = sharedProperties.getUsersInfo();
        users.forEach(function (usr) {
            if (usr.id === userid && usr.pwd === password) {
                alert("Welcome " + userid);
                sharedProperties.setAuthentication();
                sharedProperties.setCurrentUser(usr.id);
                window.location = "home.html";
            }
        })();
        if(sharedProperties.isAuthenticated() === false) {
            alert("Invalid Login");
        }
    }
});

expmodule.controller('expenseForm', function($scope, sharedProperties) {
    $scope.submitExpense = function (expenseInfo) {
        var id;
        id = sharedProperties.getCurrentUser();
        sharedProperties.setExpenseInfo(id, expenseInfo);
        alert(sharedProperties.getExpenseInfo(id));
    }
});

loginForm.$inject = ['$scope', 'sharedProperties'];
expenseForm.$inject = ['$scope', 'sharedProperties'];

services.js -

angular.module('myApp.services', [])
.service('sharedProperties', function () {
    var users = [{id: "Neha", pwd: "Neha"}, {id: "Sneha", pwd: "Sneha"}],
    authentication = false,
    expenses = {},
    currentUser = "";
    return {
        getUsersInfo: function () {
            return users;
        },
        setUserInfo: function (usr) {
            users.push(usr);
            expenses[usr.id] = [];
        },
        setAuthentication: function (user)      { authentication = true;      },
        isAuthenticated: function ()            { return authentication;      },
        setCurrentUser: function (id)           { currentUser = id;           },
        getCurrentUser: function ()             { return currentUser;         },
        getExpenseInfo: function (id)           { return expenses[id];        },
        setExpenseInfo: function (id, expense)  { expenses[id].push(expense); }
    }
});

1 个答案:

答案 0 :(得分:1)

您无法在angularjs中的不同“页面”之间共享数据。您需要为此使用任何持久存储。我建议你使用session / cookies。

编写一个服务(AuthService),它抽象底层存储(session / cookie / localstorage)并在用户登录后保存用户对象。