Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My angular app have 2 controllers. My problem is that the controllers does not keep the data when the user navigates away from the page.

How can I store the selected data on of my controllers into a data store so it can be used between other controllers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
241 views
Welcome To Ask or Share your Answers For Others

1 Answer

Option 1 - custom service

You can utilize a dedicated angular service to store and share data between controllers (services are single instance objects)

service definition

 app.service('commonService', function ($http) {

        var info;

        return {
            getInfo: getInfo,
            setInfo: setInfo
        };

        // .................

        function getInfo() {
            return info;
        }

        function setInfo(value) {
            info = value;
        }
});

usage in multiple controllers

app.controller("HomeController", function ($scope, commonService) {

    $scope.setInfo = function(value){
        commonService.setInfo(value);
    };

});


app.controller("MyController", function ($scope, commonService) {

    $scope.info = commonService.getInfo();

});

Option 2 - html5 localStorage

You can use the built-in browser local storage and store your data from anywhere

writing

$window.localStorage['my-data'] = 'hello world';

reading

var data = $window.localStorage['my-data']
// ...

Option 3 - via web server api

If you need to persist data among different users, you should save it somewhere in the server side (db / cache)

function getProfile() {
    return $http.get(commonService.baseApi + '/api/profile/');
}

function updateProfile(data) {
    var json = angular.toJson(data);
    return $http.post(commonService.baseApi + '/api/profile/', json);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...