AngularJS. CRUD Application example with AngularJS and Rails 4. Slides By: Jonathan McCarthy

Similar documents
AngularJS. CRUD Application example with AngularJS and Rails 4. Slides By: Jonathan McCarthy

3 Days Training Program

Making a live edit contact list with Coldbox REST & Vue.js

Single Page Applications

What is AngularJS. à Javascript Framework à MVC à for Rich Web Application Development à by Google

Tim Roes. Android- & inovex in Karlsruhe. GDG Karlsruhe Co-Organizer.

AngularJS. Beginner's guide - part 2

ADDING INPUTS FORM FACTORY V2

Building JSR-286 portlets using AngularJS and IBM Web Experience Factory

AngularJS AN INTRODUCTION. Introduction to the AngularJS framework

Working Bootstrap Contact form with PHP and AJAX

About the Tutorial. Audience. Prerequisites. Disclaimer & Copyright. AngularJS

Rails: MVC in action

Spring Data JPA, Spring Boot, Oracle, AngulerJS 적용게시판실습 게시판리스트보기.

CSCI-2320 Web Programming: Ruby on Rails

Project Part 2 (of 2) - Movie Poster And Actor! - Lookup

Lecture 7. Action View, Bootstrap & Deploying 1 / 40

Advantages: simple, quick to get started, perfect for simple forms, don t need to know how form model objects work

AngularJS Intro Homework

AngularJS - Walkthrough

Rails: Views and Controllers

Dingle Coderdojo 6. Project Part 2 (of 2) - Movie Poster And Actor! - Lookup. Week 6

ADVANCED JAVASCRIPT #8

JSON POST WITH PHP IN ANGULARJS

A conditional statement can compare two values. Here we check if one variable we declared is greater than another. It is true so the code executes.

By the end of this Angular 6 tutorial, you'll learn by building a real world example application:

AngularJS Introduction

THE HITCHHIKERS GUIDE TO. Harper Maddox CTO, EdgeTheory 30 September 2014

Input and Validation. Mendel Rosenblum. CS142 Lecture Notes - Input

ANGULARJS - MOCK TEST ANGULARJS MOCK TEST II

Introduction to AngularJS

Angular 2 Programming

Table of Contents EVALUATION COPY

ANGULARJS INTERVIEW QUESTIONS

This project will use an API from to retrieve a list of movie posters to display on screen.

UNIVERSITY OF TORONTO Faculty of Arts and Science APRIL 2016 EXAMINATIONS. CSC309H1 S Programming on the Web Instructor: Ahmed Shah Mashiyat

Comprehensive Angular 2 Review of Day 3

INTRODUCTION TO WEB DEVELOPMENT IN C++ WITH WT 4

Day 3: 26/April/2012 Scaffolding Generation of Skeletons; Test run Memopad

Advanced Angular & Angular 6 Preview. Bibhas Bhattacharya

Courslets, a golf improvement web service. Peter Battaglia

User manual Scilab Cloud API

FatModel Quick Start Guide

Jquery Ajax Json Php Mysql Data Entry Example

User Authentication and Session Control

Lecture 4. Ruby on Rails 1 / 49

Source. Developer Guide / forms

Contents in Detail. Foreword by Xavier Noria

Nagaraju Bende

LAMPIRAN-LAMPIRAN A. Source Code 1) Sample Controller pada HomeController.php

CMPT 165 INTRODUCTION TO THE INTERNET AND THE WORLD WIDE WEB

Rails: Associations and Validation

c360 Web Connect Configuration Guide Microsoft Dynamics CRM 2011 compatible c360 Solutions, Inc. c360 Solutions

AngularJS Examples pdf

Lecture 8. Validations & Sessions 1 / 41

Creating Web Pages Using HTML

Responsive Web Design and Bootstrap MIS Konstantin Bauman. Department of MIS Fox School of Business Temple University

AngularJS Fundamentals

Lecture 4. Ruby on Rails 1 / 52

UI Course HTML: (Html, CSS, JavaScript, JQuery, Bootstrap, AngularJS) Introduction. The World Wide Web (WWW) and history of HTML

Front-End UI: Bootstrap

Unit V- Client and Server Side Frameworks

Data Presentation and Markup Languages

TUTORIAL CRUD CODEIGNITER

Lazy Loading Techniques

User manual Scilab Cloud API

AngularJS. Beginner's guide - part 1

Manual Html A Href Onclick Submit Form

COM401 Software Engineering Laboratory

Integrating the Quotation page with your site

Dynamic Web Development

Paythru Remote Fields

PSUG National Information Exchange. Users Helping Users

Summary 4/5. (contains info about the html)

CS 155 Project 2. Overview & Part A

Documentation for Import Station

Produced by. Agile Software Development. Eamonn de Leastar

ngphotos (Grails + AngularJS)

Ten good practices for ASP.NET MVC applications

Web Focused Programming With PHP

Description: This feature will enable user to send messages from website to phone number.

CS 350 COMPUTER/HUMAN INTERACTION. Lecture 6

aint framework Documentation

JavaScript Framework: AngularJS

Guide to Integrate. ADSelfService Plus with. Outlook Web App.

A WEB APPLICATION FOR ONLINE POLLING. A Thesis. Presented to the. Faculty of. San Diego State University. In Partial Fulfillment

Chapter6: Bootstrap 3. Asst.Prof.Dr. Supakit Nootyaskool Information Technology, KMITL

Mixed Signals Using Fusion s Signals API

Mastering Modern Payments

Databases/JQuery AUGUST 1, 2018

Front End Programming

CP215 Application Design

Learn to Build Awesome Apps with Angular 2

CSC 405 Computer Security. Web Security

Connecting Angular and CFML

About Me. Name: Jonathan Brown. Job: Full Stack Web Developer. Experience: Almost 3 years of experience in WordPress development

thymeleaf #thymeleaf

Getting Started with

The Hypertext Markup Language (HTML) Part II. Hamid Zarrabi-Zadeh Web Programming Fall 2013

Frontend Frameworks. SWE 432, Fall 2016 Design and Implementation of Software for the Web

Transcription:

AngularJS CRUD Application example with AngularJS and Rails 4 1 Slides By: Jonathan McCarthy

Create a new Rails App For this example we will create an application to store student details. Create a new rails 4 app - rails new student_app Slides By: Jonathan McCarthy 2

Run the Application After creating the new application, cdange directory to the new project folder. - cd student_app Run the app - rails s Go to http://127.0.0.1:3000/ Slides By: Jonathan McCarthy 3

Create a Student Scaffold A student should have the following values: - Firstname - Lastname - Student Number - Email Address Run the following command to create the scaffold rails generate scaffold student firstname:string lastname:string student_num:string email:string Create the database (run the following command) - rake db:migrate Slides By: Jonathan McCarthy 4

Add some sample data Run the server (rails s), go to http://127.0.0.1:3000/students Add 5 students to the system Slides By: Jonathan McCarthy 5

Setup Angular Slides By: Jonathan McCarthy 6

Including Angular Go to: https://code.angularjs.org/1.3.14/ And download angular.1.3.14.zip Create a new folder in assets/javascripts named angularexternal. Extract the zip folder contents to angularexternal Slides By: Jonathan McCarthy 7

Including jquery and Angular Update the application.html.erb template to look include the following: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script src="/assets/angularexternal/angular.min.js"></script> <script src="/assets/angularexternal/angular-route.js"></script> <script src="/assets/angularexternal/angular-resource.min.js"></script> <script src="/assets/angular/controllers/student_controller.js"></script> It should look like: (next Slide) Slides By: Jonathan McCarthy 8

Including jquery and Angular Slides By: Jonathan McCarthy 9

Including Angular By adding the two gems in the previous step, this will add Angular to the web application. Update the template: ng-app="mycrudapp" <div class="maincontent" ng-view> <%= yield %> </div> Slides By: Jonathan McCarthy 10

Application.html.erb The template file should look as follows: Slides By: Jonathan McCarthy 11

Setup JS Angular files In the assets\javascripts directory, create a new folder named angular - mkdir angular - cd angular - mkdir controllers This will be used to contain the logic for the Angular functionality. Slides By: Jonathan McCarthy 12

Create a Angular Student Controller Create a new file named student_controller.js in the /assets/javascripts/angular/controllers folder. Add the following to the file: - var mycrudapp = angular.module('mycrudapp', ['ngroute', 'ngresource']); Slides By: Jonathan McCarthy 13

Factory and Providers The Factory is used to send and recieve information from out server side application. The usage of the Factory will create an object and prepoerties will be added to the object. When the object is passed to the controller, these prepoerties that are part of the object will be available in the controller for use through the Factory. See: https://docs.angularjs.org/guide/providers Slides By: Jonathan McCarthy 14

Setup the Factory Add the following to student_controller.js mycrudapp.factory('students', ['$resource',function($resource){ return $resource('/students.json', {},{ query: { method: 'GET', isarray: true }, create: { method: 'POST' } }) }]); The first Factory is named Students. We can query students or create a new student. Slides By: Jonathan McCarthy 15

Setup the Factory Add the following to student_controller.js mycrudapp.factory('student', ['$resource', function($resource){ return $resource('/students/:id.json', {}, { show: { method: 'GET' }, update: { method: 'PUT', params: {id: '@id'} }, delete: { method: 'DELETE', params: {id: '@id'} } }); }]); The second Factory is named Student and allows us to show students, update an existing student and to delete a student. This is following Rails restful resources. Slides By: Jonathan McCarthy 16

student_controller.js The file student_controller.js should now look as follows: Slides By: Jonathan McCarthy 17

Routing in Angular $routeprovider provides routing functionality to the Angular application with minimal effort. $routeprovider is the provider for the $route service. The $route service allows us to easily link controllers, templates and the URL in the address bar. The $route service can be used preserve the back and forward navigation in the browser. Slides By: Jonathan McCarthy 18

Setup the Routes Add the following to student_controller.js // This is the Routes Section mycrudapp.config([ '$routeprovider', '$locationprovider', function($routeprovider, $locationprovider) { $routeprovider.when('/students',{ templateurl: '/templates/students/index.html', controller: 'StudentListCtr' }); $routeprovider.when('/students/new', { templateurl: '/templates/students/new.html', controller: 'StudentAddCtr' }); $routeprovider.when('/students/:id/edit', { templateurl: '/templates/students/edit.html', controller: 'StudentUpdateCtr' }); $routeprovider.otherwise({ redirectto: '/students' }); } ]); Slides By: Jonathan McCarthy 19

Create the Angular Templates For this simple CRUD example, we will create the following templates: - Index.html - New.html - Edit.html - _form.html The templates will be stored in the public folder in the Rails applcation. The next slide wil detail the setup of the templates. Slides By: Jonathan McCarthy 20

Create the Angular Templates In the rails projects public folder, create a new folder named templates and in this create a folder named students. Create 4 new files in the student with the following names: - index.html - new.html - edit.html - _form.html Slides By: Jonathan McCarthy 21

Form Explination <div class="form-group" ng-class="{'has-error' : submitted && studentform.firstname.$invalid}"> <label class="control-label col-md-3">first name <span class="required">* </span> </label> <div class="col-md-4"> <input type="text" name="firstname" class="formcontrol" ng-model="student.firstname" required placeholder="first name"/> </div> <p ng-show=" submitted && studentform.firstname. $invalid" class="help-block">first name is required.</p> </div> Slides By: Jonathan McCarthy 22

_form.html <div class="form-group" ng-class="{'has-error' : submitted && studentform.firstname.$invalid}"> <label class="control-label col-md-3">first name <span class="required">* </span> </label> <div class="col-md-4"> <input type="text" name="firstname" class="form-control" ng-model="student.firstname" required placeholder="first name"/> </div> <p ng-show=" submitted && studentform.firstname.$invalid" class="help-block">first name is required.</p> </div> <div class="form-group" ng-class="{'has-error' : submitted && studentform.lastname.$invalid}"> <label class="control-label col-md-3">last name <span class="required">* </span> </label> <div class="col-md-4"> <input type="text" name="lastname" class="form-control" ng-model="student.lastname" required placeholder="last name"/> </div> <p ng-show=" submitted && studentform.lastname.$invalid" class="help-block">last name is required.</p> </div> <div class="form-group" ng-class="{'has-error' : submitted && studentform.email.$invalid}"> <label class="control-label col-md-3">email <span class="required">* </span> </label> <div class="col-md-4"> <input type="email" name="email" class="form-control" ng-model="student.email" required placeholder="test@example.com"/> </div> <p ng-show="submitted && studentform.email.$error.required" class="help-block">email is required.</p> <p ng-show="submitted && studentform.email.$error.email" class="help-block">enter valid email</p> </div> <div class="form-group"> <label class="control-label col-md-3">student Number </label> <div class="col-md-4"> <input type="text" name="student_num" class="form-control" ng-model="student.student_num" placeholder="9876543210"/> </div> <p ng-show="submitted && studentform.student_num.$invalid" class="help-block">student Number is required.</p> </div> <div class="form-group"> <div class="pull-left"> <a class="btn btn-default" href="/"> Back</a> <button type="submit" class="btn btn-primary" ng-click="submitted=true">submit</button> </div> </div> Slides By: Jonathan McCarthy 23

new.html <div class="col-md-10"> <form class="tab-pane active form-horizontal" id="first" name="studentform" novalidate ng-submit="save()"> <h3 class="block">add new student</h3> <div ng-include src="'/templates/students/_form.html'"></div> </form> </div> Slides By: Jonathan McCarthy 24

edit.html <div class="col-md-10"> <form class="tab-pane active form-horizontal" id="first" name="studentform" novalidate ng-submit="update()"> <h3 class="block">edit student</h3> <div ng-include src="'/templates/students/_form.html'"></div> </form> </div> Slides By: Jonathan McCarthy 25

index.html <br/> <div class="row"> <div class="col-md-12"> <a class="btn btn-primary" href="#/students/new">create a student</a> <h3 class="block">students</h3> <table class="table table-striped"> <tr> <th>first Name</th> <th>last Name</th> <th>student Number</th> <th>email</th> <th></th> </tr> <tr ng-hide="students.length" > <td colspan="5">no students found, Please create one.</td> </tr> <tr ng-show="students.length" ng-repeat="student in students"> <td>{{student.firstname}}</td> <td>{{student.lastname}}</td> <td>{{student.student_num}}</td> <td>{{student.email}}</td> <td> <a href="#/students/{{student.id}}/edit">edit</a> <a href="" ng-click="deletestudent(student.id)">remove</a> </td> </tr> </table> </div> </div>

Adding Controllers to the App Next we will add the Angular controllers to the application Slides By: Jonathan McCarthy 27

List Controller mycrudapp.controller("studentlistctr", ['$scope', '$http', '$resource', 'Students', 'Student', '$location', function($scope, $http, $resource, Students, Student, $location) { $scope.students = Students.query(); $scope.deletestudent = function (studentid) { if (confirm("are you sure you want to delete this student?")){ Student.delete({ id: studentid }, function(){ $scope.students = Students.query(); $location.path('/'); }); } }; }]); Slides By: Jonathan McCarthy 28

Add Controller mycrudapp.controller("studentaddctr", ['$scope', '$resource', 'Students', '$location', function($scope, $resource, Students, $location) { $scope.student = {} $scope.save = function () { if ($scope.studentform.$valid){ console.log('here' + $scope.student); //Students.create({student: $scope.student}, function(){ Students.create($scope.student, function(){ $location.path('/'); }, function(error){ console.log(error) }); } } }]); Slides By: Jonathan McCarthy 29

Update Controller mycrudapp.controller("studentupdatectr", ['$scope', '$resource', 'Student', '$location', '$routeparams', function($scope, $resource, Student, $location, $routeparams) { $scope.student = Student.get({id: $routeparams.id}) $scope.update = function(){ if ($scope.studentform.$valid){ console.log('here2' + $scope.student); Student.update($scope.student,function(){ $location.path('/'); }, function(error) { console.log(error) }); } }; }]); Slides By: Jonathan McCarthy 30

Where to place the controller code Add the code for the controllers to the student_controller.js Slides By: Jonathan McCarthy 31

CSRF Edit application_controller.rb Update /app/controllers/application_controller.rb to look as follows. The changes will allow Rails to work with the Angular app. class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception after_filter :set_csrf_cookie_for_ng def set_csrf_cookie_for_ng cookies['xsrf-token'] = form_authenticity_token if protect_against_forgery? end protected def verified_request? super form_authenticity_token == request.headers['x-xsrf-token'] end end Slides By: Jonathan McCarthy 32

Update Routes.rb Update routes.rb to look as follows: Rails.application.routes.draw do resources :students root 'students#index' end Slides By: Jonathan McCarthy 33

Run the App Run the application and test the functionality. http://127.0.0.1:3000 Slides By: Jonathan McCarthy 34

Questions Slides By: Jonathan McCarthy 35