Web Programming examples

Google Maps,AngularJS

Ruby on Rails Tutorial delete micropost with AngularJS

(1)Rails controller

$ vi app/controllers/microposts_controller.rb

  before_action :signed_in_user, only: [:create, :destroy]
  before_action :correct_user,   only: :destroy

  def destroy
    Micropost.find(params[:id]).destroy
    head :no_content
  end

(2)add link to views

$ vi app/assets/templates/static_pages/home.html.erb
$ vi app/assets/templates/users/show.html.erb

.....
<small class="text-muted">Posted {{mp.created_at | date:'medium'}}</sm
all>
<span ng-show="chkSignin().user.id == mp.user_id"><a href="" ng-click="delete(mp.id)">delete</a></span>
.....

(3)AngularJS controller

1)User Profile page "UsersShowCtrl" controller

$ vi app/assets/javascripts/mymodule.js.erb

myModule.controller("UsersShowCtrl", function($scope, $routeParams, userResource,flashService,micropostsResource) {

  $scope.chkSignin = function() {
    return flashService.getUser();
  };

  $scope.delete = function(id) {
    micropostsResource.destroy({ id: id });
    userResource.show({ id: $routeParams.id }, function(response) {
      $scope.user_info = response;
      $scope.totalitems = $scope.user_info.microposts.length;
      microposts = $filter('orderBy')($scope.user_info.microposts,'created_at',true);
      $scope.currentitems = microposts.slice(start,end);
      flashService.setUser(response);
    });
  };
});

2)Home page "HomeCtrl" controller

  $scope.delete = function(id) {
    micropostsResource.destroy({ id: id });
    sessionResource.current_user({}, function(response) {
      tmp_feed = response.feed;
      $scope.totalitems = tmp_feed.length;
      feed_items = $filter('orderBy')(tmp_feed,'created_at',true);
      $scope.currentitems = feed_items.slice(start,end);
      flashService.setUser(response);
    });
  };