javascript - 如何将标签本地保存到设备?

标签 javascript html angularjs

我正在尝试使用本地存储保存标签。它不起作用,我不知道它发生了什么。

应用程序.js:

var app = angular.module('plunker', ['ngTagsInput']);

app.controller('MainCtrl', function($scope, $http) {
  $scope.tags = [
    { text: 'Tag1' },
    { text: 'Tag2' },
    { text: 'Tag3' }
  ];
});

index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <link rel="stylesheet" href="http://mbenford.github.io/ngTagsInput/css/ng-tags-input.min.css" />
    <script data-require="angular.js@1.2.x" src="http://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.15"></script>
    <script src="http://mbenford.github.io/ngTagsInput/js/ng-tags-input.min.js"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <tags-input ng-model="tags"></tags-input>
    <p>Model: {{tags}}</p>
  </body>

</html>

我正在尝试使用 localStorage 执行此操作,以便在用户离开应用程序、返回到另一个页面或只是刷新它时让标签保留在那里。

window.localStorage['name'] = {{tags}};

文档链接: http://learn.ionicframework.com/formulas/localstorage/

最佳答案

您需要将标签模型保存到 localStorage 并在每次集合更改时更新它:删除/添加标签。为此创建辅助服务很方便:

var app = angular.module('plunker', ['ngTagsInput']);

app.controller('MainCtrl', function($scope, $http, storage) {
    $scope.tags = storage.get('tags') || [
        { text: 'Tag1' },
        { text: 'Tag2' },
        { text: 'Tag3' }
    ];

    $scope.$watchCollection('tags', function(tags) {
        storage.set('tags', tags);
    });
});

app.factory('storage', function() {
    return {
        get: function(key) {
            return JSON.parse(localStorage[key] || 'null');
        },
        set: function(key, value) {
            window.localStorage[key] = JSON.stringify(value);
        }
    };
});

请注意,如何在 Controller 代码中首先检查存储的项目,如果不可用则回退到默认标签:

$scope.tags = storage.get('tags') || [
    { text: 'Tag1' },
    { text: 'Tag2' },
    { text: 'Tag3' }
];

演示: http://plnkr.co/edit/jgJNADUuTsgbTNvK16Jg?p=preview

关于javascript - 如何将标签本地保存到设备?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31241639/

相关文章:

javascript - 根据react-native中传递的参数设置动态名称

javascript - CSS 媒体查询和 jQuery 窗口 .width() 不匹配

html - div 粘在页面顶部的小问题

javascript - Knockout - 无法处理绑定(bind) - 带有

javascript - 我不知道这个表格 "action"是什么意思

javascript - AngularJS - 动态添加表行中的所有值

javascript - 我收到错误 : ER_SP_UNDECLARED_VAR: Undeclared variable: NaN when trying AJAX request with jQuery

java - 在客户端处理 session 超时

android - Firebase - 是否有 API 可以在 firebase 上运行清理脚本

javascript - AngularJS - 页面在尝试从 url 获取参数时重定向到 angular js 中的其他页面