Skip to content

Instantly share code, notes, and snippets.

@goranprijic
Last active August 29, 2015 14:22
Show Gist options
  • Save goranprijic/b35b83090b47905ba6d3 to your computer and use it in GitHub Desktop.
Save goranprijic/b35b83090b47905ba6d3 to your computer and use it in GitHub Desktop.
Example of bad Model layer in angular (written for presentation)
// Post Model
angular.module('myApp')
.factory('Post', function($resource) {
var resource = $resource(
'/posts/:id',
{
id: '@id'
},
{
'store': { method: 'POST' },
'update': { method:'PUT' },
'destroy': { method:'DELETE' }
}
);
return resource;
});
// Comment Model
angular.module('myApp')
.factory('Comment', function($resource) {
var resource = $resource(
'/comments/:postId/posts/:id',
{
id: '@id',
postId: '@postId'
},
{
'store': { method: 'POST' },
'update': { method:'PUT' },
'destroy': { method:'DELETE' }
}
);
resource.prototype.isDeletable = function() {
return this.is_published && !this.deleted_at;
};
return resource;
});
// list posts controller
angular.module('myApp')
.controller('ListPostsCtrl', function ($scope, Post, posts, user) {
$scope.posts = posts;
$scope.newPost = new Post({
user_id: user.id
});
$scope.addPost = function(post) {
post.$store();
$scope.posts.push(post);
};
$scope.deletePost = function (post) {
_.remove($scope.posts, {id: post.id});
if (post.id) {
post.$destroy();
}
};
$scope.$onRootScope('socket.posts.deleted', function(event, post) {
_.remove($scope.posts, {id: post.id});
});
// ...
});
// comments controller
angular.module('myApp')
.controller('PostCommentsCtrl', function ($scope, Post, Comment, post, comments, user) {
$scope.post = post;
$scope.comments = comments;
$scope.newComment = new CommentModel({
user_id: user.id
});
$scope.commentsAllowed = function () {
return $scope.post.comments_allowed && $scope.post.is_published;
};
$scope.hasComments = function () {
return $scope.commentsAllowed() && this.comments.length;
};
$scope.addComment = function (comment) {
if ($scope.commentsAllowed()) {
comment.$store();
this.comments.push(comment);
}
};
$scope.deleteComment = function (comment) {
// comment is not instance of Comment so we can't call isDeletable
if (comment.is_published && !comment.deleted_at) {
_.remove(this.comments, {id: comment.id});
// we can't call comment.$destroy
Comment.destroy({}, {'id' : comment.id});
}
};
// ....
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment