gpt4 book ai didi

javascript - 数组更新后 Ng-Repeat 不更新

转载 作者:行者123 更新时间:2023-11-30 17:07:09 25 4
gpt4 key购买 nike

我有一个数组,其中包含要循环遍历的模板中的卡片对象。如果它检测到本地数据存储中没有任何内容,它将创建一个包含对象的数组。否则,它会从本地数据存储中检索它。按下按钮会将您带到共享同一 Controller 的另一个 View 。有一个文本框,如果您按下提交按钮,它将把它拼接到数组中。如果检测到变化,我还有一个更新本地数据存储的监视功能。

问题是在向数组添加内容后 ng-repeat 不会更新。如果我仅因为本地数据存储加载而刷新页面,它就会执行。

有什么想法吗?

代码:controllers.js

.controller('NotesCtrl', function($scope, localStorageService) {
if (!localStorageService.get("agendaNotes")) {
$scope.notes = [{
title: "Civil War Notes"
}, {
title: "Types of Bacon"
}];
//If it exists retrieve it from keystore.
} else {
$scope.notes = localStorageService.get("agendaNotes");
}

$scope.addNote = function(title) {
$scope.notes.splice(0, 0, {
title: title
})
};

$scope.$watch("notes", function(newVal, oldVal) {
if (newVal !== null && angular.isDefined(newVal) && newVal !== oldVal) {
localStorageService.add("agendaNotes", angular.toJson(newVal));
}
}, true);

})

tab.notes.html

<ion-view view-title="Notes">
<ion-content class="padding" ng-init="init()">
<!-- To Do List for Notes:

- Store Text in Object
- Phonegap Camera API
- Store Image in Object
-->

<a class="button button-full button-royal" href="#/tab/new">
Add Notecard
</a>

<div class="card" ng-repeat="note in notes track by $index">
<div class="item item-divider">
{{note.title}}
</div>
<div class="item item-text-wrap">
{{note.content}} </div>
</div>
</ion-content>
</ion-view>

新笔记.html

<ion-view view-title="New Note">
<ion-content>
<!-- To Do:
- Description
- Images (?)
-->
<form ng-submit="addNote(data.newTitle, data.newDescription); data.newTitle = ''; data.newDescription = ''">
<div class="list">
<div class="list list-inset">
<h3>Note Title:</h1>
<label class="item item-input">
<input type="text" placeholder="Title" ng-model="data.newTitle">
</label>
<h3>Note Description:</h3>
<label class="item item-input">
<input type="text" placeholder="Description" ng-model="data.newDescription">
</label>
</div>
<button class="button button-block button-positive" type="submit">
Add Note
</button>
</div>
</form>
</ion-content>
</ion-view>

我已经尝试了 $scope.$apply(function(){}) 方法,它在控制台中返回错误:错误:[$rootScope:inprog] $apply already in progress

感谢任何帮助。谢谢

最佳答案

我认为这是由于子范围问题造成的,Mark Rajcok 在另一个类似问题上有很好的答案 - Using the same controller on different elements to refer to the same object

简而言之,他写道

“每次 Angular 编译器在 HTML 中找到 ng-controller 时,都会创建一个新的范围。(如果你使用 ng-view,每次你转到不同的路线时,也会创建一个新的范围。)

如果您需要在 Controller 之间共享数据,通常服务是您的最佳选择。将共享数据放入服务中,并将服务注入(inject) Controller :"

关于javascript - 数组更新后 Ng-Repeat 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27770402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com