AngularJS ng repeat没有't在LocalStorage更改时更新(使用store.js)
AngularJS ng-repeat doesn't update when LocalStorage is changed (using store.js)
在我的视图中,我想显示保存在LocalStorage元素中的项目列表(主题名称)。我在视图中的代码如下:
<div class="list">
<a class="item" href="#" ng-repeat="subject in subjects">
{{subject.name}}
</a>
</div>
我的控制器是这样的:
.controller('SubjectCtrl', function ( $scope ) {
$scope.subjects = store.get('subjects');
$scope.submit = function() {
if (store.get('subjects') != null) {
var existing = store.get('subjects')
var subject = [ { name: $scope.form.name, weighting: $scope.form.weighting, grades: [] } ]
subject.add(existing)
store.set('subjects', subject)
}
else {
var subject = [ { name: $scope.form.name, weighting: $scope.form.weighting, grades: [] } ]
store.set('subjects', subject)
}
};
})
$scope.subjects变量使用Store.js从LocalStorage获取项目(https://github.com/marcuswestin/store.js,一个简化LocalStorage访问的插件),并将它们提供给视图。
当用户提交表单以添加新主题时,会触发下面的代码。表单包含两个输入:名称和权重。提交表单时,代码会检查LocalStorage对象"subjects"中是否已经有任何主题。如果是,则将新主题添加到主题阵列中,并更新LocalStorage。否则,将创建名为"subjects"的LocalStorage对象,并添加新主题。
上面的代码按预期工作,但我的大问题是,如果在LocalStorage内的阵列中添加了新主题,Angular不会更新视图,我必须手动重新加载页面才能看到新主题出现在列表中。
经过一些研究,我了解到问题可能是由于LocalStorage对象在AngularJS的范围之外更新而导致的。但我是Angular的初学者,不知道在对象发生变化时通知Angular的最佳方式是什么。
我感谢任何帮助!
-更新--
我已经从store.js(与angular配合不好)切换到ngStorage(https://github.com/gsklee/ngStorage)。如果我使用ngStorage:发布我更新的控制器代码,也许这对某人有帮助
.controller('SubjectCtrl', function ( $scope, $localStorage ) {
$scope.$localStorage = $localStorage.$default({
subjects: []
});
$scope.subjects = $localStorage.subjects;
$scope.submit = function() {
$localStorage.subjects.push({ name: $scope.form.name, weighting: $scope.form.weighting, grades: [] });
};
})
您的代码中有几点可以改进——最重要的是:您永远不会通知$scope
更改。试试这个,让我知道它是否有帮助:
.controller('SubjectCtrl', function ( $scope ) {
$scope.subjects = store.get('subjects');
if($scope.subjects == null) {
$scope.subjects = [];
}
$scope.submit = function() {
$scope.subjects.push({ name: $scope.form.name, weighting: $scope.form.weighting, grades: [] });
store.set('subjects', $scope.subjects)
};
})
-更新--
找到的解决方案OP在更新的问题中,高于
- $rootScope未使用forEach进行更新
- 使用AngularJS中的筛选器更新给定的表
- 使用mongodb更新中的一个变量
- 无法在现有状态转换期间更新-未使用任何非法的setState()
- 使用它更新集合中的嵌套数组's索引
- 使用Javascript更新输入框中的文本
- 如何在范围值更改时使用 angularJs 更新 UI
- 使用rows().eevery().remove()时未更新行索引
- AngularJS ng repeat没有't在LocalStorage更改时更新(使用store.js)
- 我可以更新使用 innerhtml 显示的 javascript 变量吗?
- 记分牌不会更新 -- 使用 JavaScript 的 RPS 游戏
- angularjs,范围不跨功能更新-使用ngTouch
- HTML输入AJAX更新-使用Bootstrap将样式添加到输入字段
- 什么是最不丑陋的方式来强迫骨干.同步更新使用POST而不是PUT
- Knockout不会更新使用ko.mapping制作的模型中的字符串数组
- Select不会自动更新使用ng-repeat呈现的ng-model更改
- 如何克隆、更新& &;使用JavaScript附加一个变量
- PHP更新使用Javascript
- 更新:使用Javascript/Jquery改变负预定值的颜色
- 编辑字段后如何更新(使用jquery或javascript)'的值