Web Programming examples

Google Maps,AngularJS

Ruby on Rails Tutorial updating users with AngularJS

(1)Rails controller

$ vi app/controllers/users_controller.rb

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(user_params)
      render json: @user, status: :created, location: @user
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end

(2)AngularJS route

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

myModule = angular.module('myModule', ['ui.bootstrap','ngRoute','ngResource']);

myModule.config(function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider
........
    .when("/users/:id/edit", {
     templateUrl: "<%= asset_path('users/new.html.erb') %> "
     })

(3)AngularJS controller

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

myModule.controller("UsersNewCtrl", function($scope, userResource, $location, flashService, $routeParams) {
  if ($routeParams.id) {
    var msg = "Profile updated";
    $scope.title = "Update your profile";
    $scope.btn_name = "Save changes";
    userResource.show({ id: $routeParams.id }, function(user_info) {
      $scope.user = user_info.user;
      $scope.gravatar_url = user_info.gravatar_url;
    })
  } else {
    var msg = "Welcome to the Sample App!";
    $scope.title = "Sing up";
    $scope.btn_name = "Create my account";
    $scope.user = new userResource();
  }
  $scope.submit = function() {
.......
    if ($routeParams.id) {
      userResource.update($scope.user, success, failure);
    } else {
      userResource.create($scope.user, success, failure);
    }
  };

ref.
Rails controller 

  def show
    user = User.find(params[:id])
    gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
    @user_info = {
      user: user,
      gravatar_url: "https://secure.gravatar.com/avatar/#{gravatar_id}"
    }
    render json: @user_info
  end

(4)AngularJS template view

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

<h1 class="text-center">{{title}}</h1>
.....
<button ng-click="submit()" class="btn btn-primary"
         ng-disabled="userNewForm.$invalid" >
  {{btn_name}}
</button>
......
<span ng-show="user.id">
  <img alt="{{user.name}}" src="{{gravatar_url}}" />
  <a href="http://gravatar.com/emails">change</a>
</span>

(5)add link to navigation menu

$ vi app/views/layouts/_header.html.erb

<li><%= link_to "Settings", "/users/{{chkSignin().user.id}}/edit" %></li>