AngularJS – Using $resource for Data Models




  
  

  
  




  

Posts

Title
{{post.title}}

New Post

Edit Post

controllers/main.js

angular.module('app')
  .controller('MainCtrl', ['$scope', '$route', 'Post',
      function($scope, $route, Post) {

        $scope.post = new Post();
        $scope.posts = Post.query();

        $scope.newPost    = function() {
          $scope.post = new Post();
          $scope.editing = false;
        }

        $scope.activePost = function(post) {
          $scope.post = post;
          $scope.editing = true;
        }

        $scope.save = function(post) {
          if ($scope.post._id) {
            Post.update({_id: $scope.post._id}, $scope.post);
          } else {
            $scope.post.$save().then(function(response) {
              $scope.posts.push(response)
            });
          }
          $scope.editing = false;
          $scope.post = new Post();
        }

        $scope.delete = function(post) {
          Post.delete(post)
          _.remove($scope.posts, post)
        }

      }
  ]);

models/post.js

angular.module('app')
  .provider('Post', function() {
    this.$get = ['$resource', function($resource) {
      var Post = $resource('http://localhost:3000/api/post/:_id', {}, {
        update: {
          method: 'PUT'
        }
      })

      return Post;
    }];
  });