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

How to save tags locally to device?

本文关键字:保存 标签      更新时间:2023-09-26

我正在尝试用本地存储保存标签。它不起作用,我不知道它是怎么回事。

app.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);
        }
    };
});

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

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

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

此代码将从localStorage读取标签,并将其放入控制器中

$scope.tags = JSON.parse(window.localStorage['tags'] || '[]');

此代码将把标签保存到本地存储:

window.localStorage['tags'] = JSON.stringify($scope.tags);

例如,您的控制器将是这样的:

app.controller('MainCtrl', function($scope, $http) {
   $scope.tags = JSON.parse(window.localStorage['tags'] || '[]');
  //Another methods
});