在我的控制器中:
通过单击元素,将信息提供给tabNameStore。 数据按名称显示为html
$scope.openTab = function($event){
//Checks for doubles
if($scope.tabNameStore.length>0){
for(var i=0; i<$scope.tabNameStore.length; i++){
if($scope.tabNameStore[i].id == $event.currentTarget.id){
console.log("Already open");
return;
}
}
}
//Saves name, ID and number
$scope.tabNameStore[count] = ({name: $event.currentTarget.innerHTML,
id: $event.currentTarget.id, num: count++});
//Tries to get item by id
var local = localStorage.getItem($event.currentTarget.id);
//If not stored in local, it does so
if (local == null){
localStorage.setItem($event.currentTarget.innerHTML,
$scope.tabNameStore[count-1].name);
localStorage.setItem($event.currentTarget.id,
$scope.tabNameStore[count-1].id);
console.log("null");
} else{
console.log("not null");
return;
}
}
将来自localStorage的数据保存回tabNameStore
$window.onload = function() {
var archive = [];
archive = allStorage();
count = 0;
for(var i=0; i<archive.length/2; i++){
if(archive[i] != null){
$scope.tabNameStore[count] = ({name: archive[i], id:
archive[i+archive.length/2], num: count++});
}
}
}
从localStorage获取所有数据
function allStorage() {
var keys = Object.keys(localStorage); // Gibt alle Schlüssel zurück
var archive = [];
for (var i=0; i< keys.length; i++) {
archive.push(keys[i]);
}
return archive;
}
HTML是:
<article id="default">
<div id="heading">
<a href="###" class="tab" id="desktop" >Desktop</a>
<a href="###" class="tab" id="" data-ng-repeat="y in
tabNameStore" data-ng-click="" >{{y.name}}</a>
</div>
<div class="gridly toggle" id="Desktop">
<div class="brick small" draggable="true" data-letters="
{{x.name[0]}}" id="{{x.id}}" data-ng-repeat="x in storage |
orderBy: '-name'" data-ng-click="openTab($event)">
{{x.name}}
</div>
</div>
</article>
重新加载页面并从localStorage获取数据后,即使数组已填充,它仍然不会显示。只需再次单击其中一个元素(openTab函数),就可以立即显示存储在localStorage中的所有元素。
答案 0 :(得分:0)
我解决了:
通过在重新加载数组的部分周围添加$scope.$apply
:
....
$scope.$apply(function(){
for(var i=0; i<archive.length/2; i++){
if(archive[i] != null){
$scope.tabNameStore[count] = ({name: archive[i], id:
archive[i+archive.length/2], num: count++});
}
}
});
....
像这样,重新加载后为angularjs设置了更新后的数组。