在我的视图中,我想显示保存在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在更新的问题中,高于