[英]How to use localstorage to send data into another html file(NOT SPA) - angularjs
我沒有使用SPA應用程序,因此,如果我單擊頁面加載的另一個html文件,則無法捕獲數據,我想存儲在該localstorage中。
這是我的控制器文件:
angular
.module('myApp', [])
.controller('myController', function($scope, $rootScope) {
$scope.users = [{
name: 'sameer',
age: 21
},
{
name: 'ganesh',
age: 22
}
]
$scope.setcontactModal = function(user) {
$scope.modalcontactData = user;
}
});
我的第一個索引頁面:
<body ng-controller='myController'>
<table class="table">
<tr>
<th>Name</th>
<th>Age</th>
<th>Operations</th>
</tr>
<tr ng-repeat='user in users'>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td> <a href="edit.html" ng-click='setcontactModal(user)'> Apply </a> </td>
</tr>
</table>
</body>
我想將此$ scope.modalcontactData共享到另一個名為edit.html文件的文件中:
這是我另一個名為edit.html的 html文件。
<body ng-controller='myController'>
<p>hello {{modalcontactData}} </p>
</body>
我嘗試了這個:
angular
.module('myApp', ['ngStorage'])
.controller('myController', function($scope, $rootScope,$localStorage) {
$scope.users = [{
name: 'sameer',
age: 21
}, {
name: 'ganesh',
age: 22
}]
$localStorage.modalcontactData = $scope.modalcontactData;
$scope.setcontactModal = function(user) {
$scope.modalcontactData = user;
console.log('scope:', $scope.modalcontactData);
}
});
就您而言,您可以像這樣使用本地存儲。
工作演示: https : //plnkr.co/edit/84V6v7qkeE62hI1eU0eu
angular .module('myApp', ['ngStorage']) .controller('myController', function($scope, $rootScope) { $scope.modalcontactData=JSON.parse(window.localStorage.getItem("user")) $scope.users = [{ name: 'sameer', age: 21 }, { name: 'ganesh', age: 22 }] $scope.setcontactModal = function(user) { $scope.modalcontactData = user; window.localStorage.setItem("user",JSON.stringify(user)); console.log('scope:', $scope.modalcontactData); } });
如果要將數據存儲在本地存儲中,則可以使用本地草料庫,這是一個非常有用的庫,用於以json格式存儲和檢索數據。
只需將此文件添加到您的index.html https://github.com/localForage/localForage/blob/master/dist/localforage.js
<script src="js/localforage.js"></script>
現在您可以使用這些簡單的功能輕松地以json格式存儲或從本地存儲中檢索數據。要保存數據,您可以使用-
localforage.setItem("modelContactData", user);
並檢索數據使用-
localforage.getItem("modelContactData",function(err,data){
console.log(data);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.