使用Spring MongoDB AngularJS开发一个单页应用
使用Spring MongoDB AngularJS开发一个单页应用源码下载这个应用的演示地址:http://getbookmarks-shekhargulati.rhcloud.com/#/
当用户进入到上面'/'URL的应用,那么用户将看到一个排序的故事列表,数据来自MongoDB,AngularJS发出REST(/ api/v1/stories)调用来获取所有的故事列表。
当用户 点按一个story故事时进入后,会看到故事的详细, AngularJS 会实现一个RESTful GET 请求(/api/v1/stories/528b9a8ce4b0da0473622359) 来抓取整个story.
用户可以提交一个新的故事,AngularJS POST后端RESTful然后保存故事在 MongoDB datastore.
模型代码:
@Document(collection = "stories")
public class Story {
@Id
private String id;
private String title;
private String text;
private String url;
private String fullname;
private final Date submittedOn = new Date();
private String image;
public Story() {
}
// Getter and Setter removed for brevity
angularJS的架构图:
首页index.html:
<!DOCTYPE html>
<html ng-app="getbookmarks">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="css/bootstrap.css"/>
<link rel="stylesheet" href="css/toastr.css"/>
<style>
body {
padding-top: 60px;
}
</style>
<title>GetBookmarks : Submit Story</title>
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="brand" href="#">GetBookmarks</a>
</div>
</div>
</div>
<div class="container" ng-view>
</div>
<script src="js/jquery-1.9.1.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/angular.js"></script>
<script src="js/angular-resource.js"></script>
<script src="js/toastr.js"></script>
<script src="js/app.js"></script>
</body>
</html>
angular代码:
angular.module("getbookmarks.services", ["ngResource"]).
factory('Story', function ($resource) {
var Story = $resource('/api/v1/stories/:storyId', {storyId: '@id'});
Story.prototype.isNew = function(){
return (typeof(this.id) === 'undefined');
}
return Story;
});
angular.module("getbookmarks", ["getbookmarks.services"]).
config(function ($routeProvider) {
$routeProvider
.when('/', {templateUrl: 'views/stories/list.html', controller: StoryListController})
.when('/stories/new', {templateUrl: 'views/stories/create.html', controller: StoryCreateController})
.when('/stories/:storyId', {templateUrl: 'views/stories/detail.html', controller: StoryDetailController});
});
function StoryListController($scope, Story) {
$scope.stories = Story.query();
}
function StoryCreateController($scope, $routeParams, $location, Story) {
$scope.story = new Story();
$scope.save = function () {
$scope.story.$save(function (story, headers) {
toastr.success("Submitted New Story");
$location.path('/');
});
};
}
function StoryDetailController($scope, $routeParams, $location, Story) {
var storyId = $routeParams.storyId;
$scope.story = Story.get({storyId: storyId});
}