我正在尝试在我的网站上创建一个静态博客。我有一个json文件,其中包含要显示的帖子。 然后我有一个模态窗口,我将在其中创建一个新帖子。 我可以看到结果,网站显示新帖子,但是当重新加载页面时,新帖子就消失了。 我想在不使用后端的情况下更新json文件,只使用angularjs,是否可能?
我尝试了这个没有成功:
Posts.html:
<div class="row" data-ng-repeat="post in posts">
<div class="col-md-1 text-center">
<p>June 17, 2014</p>
</div>
<div class="col-md-5">
<a ui-sref="/posts/{{ posts.indexOf(post) }}">
<img class="img-responsive img-hover" src="http://placehold.it/600x300" alt="">
</a>
</div>
<div class="col-md-6">
<h3>
<a href="#/post/{{ posts.indexOf(post) }}">{{ post.title }}</a>
</h3>
<p>by <a href="#/post/{{ posts.indexOf(post) }}">{{ post.author }}</a>
</p>
<p>{{ post.exerpt }}</p>
<a class="btn btn-primary" href="#/post/{{ posts.indexOf(post) }}">Read More <i class="fa fa-angle-right"></i></a>
</div>
<br/>
<hr>
</div>
<button class="btn btn-success" ng-click="showModal()">Add New Post</button>
Posts.js:
.controller('PostsCtrl', ['$scope', '$http', '$modal', function($scope, $http, $modal){
$http.get('data/posts.json').success(function(data){
$scope.posts = data;
});
$scope.showModal=function () {
$scope.newPost={};
var modalInstance = $modal.open({
url:'/addpost',
templateUrl: 'views/addpost.html',
controller:'AddpostCtrl',
resolve: {
newPost: function() {
return $scope.newPost;
}
}
});
modalInstance.result.then(function(selectedItem) {
$scope.posts.push({
author: $scope.newPost.author,
title: $scope.newPost.title,
exerpt: $scope.newPost.exerpt,
content: $scope.newPost.content
});
});
};
}]);
addpost.html:
<div class="modal-header">
<button type="button" class="close" ng-click="cancel()" data-dismiss="modal" aria-hidden="true">×</button>
<h1>New Post</h1>
</div>
<div class="modal-body">
<label>Author</label><input type="text" ng-model="newPost.author"/>
<label>Title</label><input type="text" ng-model="newPost.title"/>
<label>Summary</label><textarea type="text" ng-model="newPost.exerpt"/>
<label>Content</label><textarea type="text" ng-model="newPost.content"/>
<br/>
<button class="btn btn-success" ng-click="addNewPost()"> Add Post</button>
</div>
addpost.js:
.controller('AddpostCtrl',['$scope', '$modalInstance','newPost','$http', function ($scope, $modalInstance,newPost,$http) {
$scope.newPost=newPost;
$scope.addNewPost=function(newPost){
$http.get('data/posts.json').success(function(data){
$scope.posts = data;
$scope.posts.push({newPost: newPost});
});
$modalInstance.close(newPost);
};
$scope.cancel =function(){
$modalInstance.dismiss('cancel');
};
}]);
我不知道是否可以使用角度局部存储或任何其他解决方案。
非常感谢你的帮助!!!!