Skip to content

Instantly share code, notes, and snippets.

@goranprijic
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save goranprijic/421e380ee4742f7e91d4 to your computer and use it in GitHub Desktop.
Save goranprijic/421e380ee4742f7e91d4 to your computer and use it in GitHub Desktop.
ngNestedResource-example (written for presentation)
// Post Model
angular.module('MyApp')
.factory('PostModel', function(BaseModel) {
var PostModel = BaseModel(
'/posts/:id',
{
id: '@id'
},
{
comments: 'CommentModel'
}
);
PostModel.commentsAllowed = function () {
return this.comments_allowed && this.is_published;
};
PostModel.prototype.addComment = function (comment) {
if (this.commentsAllowed()) {
this.comments.push(comment);
}
return false;
};
PostModel.prototype.hasComments = function () {
return this.commentsAllowed() && this.comments.length;
};
PostModel.prototype.deleteComment = function (comment) {
if (comment.isDeletable()) {
this.comments.remove(comment);
}
};
return PostModel;
});
// Comment Model
angular.module('MyApp')
.factory('CommentModel', function(BaseModel) {
var CommentModel = BaseModel(
'/posts/:postId/comments/:id',
{
id: '@id',
postId: '@postId'
}
);
CommentModel.prototype.isDeletable = function() {
return this.is_published && !this.deleted_at;
};
return CommentModel;
});
// Posts Collection
angular.module('MyApp')
.factory('PostsCollection', function(BaseCollection, PostModel, $rootScope) {
var PostsCollection = BaseCollection(
PostModel,
// TODO not yet implementd but can be added as some "watch" callback
function () {
$rootScope.$onRootScope('socket.posts.deleted', function(event, post) {
_.remove(collection, {id: post.id});
});
}
);
return PostsCollection;
});
// Comments Collection
angular.module('MyApp')
.factory('CommentsCollection', function(BaseCollection, CommentModel) {
var CommentsCollection = BaseCollection(CommentModel);
return CommentsCollection;
});
// list posts controller
angular.module('myApp')
.controller('ListPostsCtrl', function ($scope, PostModel, posts) {
$scope.posts = posts; // PostsCollection object
$scope.newPost = new PostModel();
// dealing with collections
$scope.addPost = function(post) {
$scope.posts.push(post);
};
$scope.deletePost = function (post) {
// controller logic like confirmation ask
$scope.posts.remove(post);
};
// ....
});
// comments controller
angular.module('myApp')
.controller('PostCommentsCtrl', function ($scope, PostModel, CommentModel, post, user) {
$scope.post = post;
$scope.newComment = new CommentModel({
user_id: user.id
});
$scope.addComment = function (comment) {
// controller logic like confirmation ask
$scope.post.addComment(comment);
};
$scope.deleteComment = function (comment) {
// controller logic like confirmation ask
$scope.post.deleteComment(comment);
};
// ....
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment