如何将此angularJS保存到HTML5 localStorage

时间:2016-06-05 12:40:08

标签: angularjs local-storage

随意告诉我离开(我是角度和javascript的新手),但我如何开始将此angularJS保存到localStorage?是否可以通过在add()中创建保存函数来相对轻松地完成某些操作?我已经看到角度有自己的本地存储但是没有它可以这样做吗?笔:http://codepen.io/kiddigit/pen/LZVXMV

angular.module('app', []);

angular.module('app').controller("MainController", function(){
    var vm = this;
    vm.title = 'Movie Database';
    vm.searchInput = '';
    vm.shows = [
        {
            title: 'Game of Thrones',
            actor: 'Dudes',
            year: 2011,
            favorite: true
        },
        {
            title: 'Walking Dead',
            actor: 'More dudes',
            year: 2010,
            favorite: false
        },
        {
            title: 'The Goonies',
            actor: 'The Coreys',
            year: 2002,
            favorite: true
        },
        {
            title: 'Firefly',
            actor: 'Dunno',
            year: 2002,
            favorite: false
        },
        {
            title: 'Bullit',
            actor: 'McQueen',
            year: 2013,
            favorite: true
        },
    ];
    vm.orders = [
        {
            id: 1,
            title: 'Year Ascending',
            key: 'year',
            reverse: false
        },
        {
            id: 2,
            title: 'Year Descending',
            key: 'year',
            reverse: true
        },
        {
            id: 3,
            title: 'Title Ascending',
            key: 'title',
            reverse: false
        },
        {
            id: 4,
            title: 'Title Descending',
            key: 'title',
            reverse: true
        }   
    ];
    vm.order = vm.orders[0];

    vm.new = {};
    vm.addShow = function() {
        vm.shows.push(vm.new);
        vm.new = {};
    };
});

1 个答案:

答案 0 :(得分:2)

浏览器(窗口对象)有一个名为localStorage的对象,就像那样简单。如果要将对象保存到本地存储,最好先使用json对其进行字符串化。

<强> 实施例

//在控制器内:

function saveMovie() {
  var selectedMovieString = json.stringify(this.selectedMovie); // for  example;
  localStorage.setItem("selectedMovie", selectedMovieString);
}