Web Programming examples

Google Maps,AngularJS

Ruby on Rails Tutorial show follow/unfollow buttons with AngularJS

1)AngularJS template view

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

<div class="col-xs-6 col-sm-8">
  <div ng-show="!flg_follers && chkSignin() && 
       chkSignin().user.id != user_info.user.id" class="row">
    <div ng-show="flg_unfollow">
      <a class="btn btn-large btn-primary" href="#" 
         ng-click="unfollow(user_info.user.id)">
        Unfollow
      </a>
    </div>
    <div ng-hide="flg_unfollow">
      <a class="btn btn-large btn-primary" href="#" 
        ng-click="follow(user_info.user.id)">follow</a>
    </div>
  </div>

2)AngularJS controller

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

myModule.controller("UsersShowCtrl", function($scope, $routeParams, userResource, flashService, $filter, micropostsResource, $q) {
  var qgetUser = function(deferred) {
    if (flashService.getUser()) {
      var quser_info = flashService.getUser();
      deferred.resolve(quser_info);
    } else {
      sessionResource.current_user({}, function(response) {
        if (response.user.id) {
          var quser_info = response;
        } else {
          var quser_info = { user: {id: 0} };
        }
        flashService.setUser(quser_info);
        deferred.resolve(quser_info);
      });
    }
  }

  var chkUnfollow = function() {
    $scope.flg_unfollow = false;
    var deferred = $q.defer();
    deferred.promise.then(function (result) {
      var user_signin = result.user.id;
      for (var i=0; i<=$scope.user_info.followers.length; i++) {
        if ($scope.user_info.followers[i] && $scope.user_info.followers[i].id == user_signin) {
          $scope.flg_unfollow = true;
        }
      }
    },function (reason) {
      console.log("user_signin-Error");
    },function (reason) {
      console.log("user_signin");
    })
    qgetUser(deferred);
  };

  userResource.show({ id: $routeParams.id }, function(response) {
    $scope.user_info = response;
    chkUnfollow();
........
  });

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.