0% found this document useful (0 votes)
51 views38 pages

Project Report: Web Development Using Angular Js and Ruby On Rails

The document provides information on developing a web application using the AngularJS and Ruby on Rails frameworks. It discusses: - AngularJS is a structural framework for dynamic web apps that uses HTML as a template language and allows extending HTML syntax. - Ruby on Rails is a full-stack web application framework that uses the Model-View-Controller pattern and includes everything needed to build database-driven web applications with less code. - The project implements using these technologies together to develop modern websites and explains how it is more effective than other options.

Uploaded by

harsh gaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views38 pages

Project Report: Web Development Using Angular Js and Ruby On Rails

The document provides information on developing a web application using the AngularJS and Ruby on Rails frameworks. It discusses: - AngularJS is a structural framework for dynamic web apps that uses HTML as a template language and allows extending HTML syntax. - Ruby on Rails is a full-stack web application framework that uses the Model-View-Controller pattern and includes everything needed to build database-driven web applications with less code. - The project implements using these technologies together to develop modern websites and explains how it is more effective than other options.

Uploaded by

harsh gaur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

PROJECT REPORT

WEB DEVELOPMENT
USING ANGULAR JS AND RUBY ON RAILS

MADE BY: ABHINAV RAJ


i
ABSTRACT

The project “Angular js with Ruby On Rails” is implemented to show how modern day website
are developed using this technology and how this method is effective than other modern day
trechnologies.

ii
ACKNOWLEDGMENT

It gives us great pleasure to express our sincere feelings of gratitude to all those, whose
invaluable guidance and useful suggestions helped us to complete this project successfully. . We
are also indebted to our guide Mr. Prashant Kumar who is responsible for the achievement of the
goal. We here by acknowledge our gratitude to all of them who were directly or indirectly
involved in carrying out this project.

ABHINAV RAJ

iii
INDEX

 INTRODUCTION
 IMPLEMENTATION
 AngularJS
 FEATURES
 CONCEPT
 ADVANTAGES OF AngularJS
 DISADVANTAGES OF AngularJS
 AngularJS COMPONENTS
 SCOPE
 CONCLUSION AND FUTURE ENHANCEMENT

iv
INTRODUCTION

AngularJS is a structural framework for dynamic web apps. With AngularJS, designers can use
HTML as the template language and it allows for the extension of HTML's syntax to convey the
application's components effortlessly. Angular makes much of the code you would otherwise
have to write completely redundant.
Despite the fact that AngularJS is commonly related to SPA, you can use Angular to build any
kind of app, taking advantage of features like: Two-way binding, templating, RESTful api
handling, modularization, AJAX handling, dependency injection, etc.

What is Ruby?
Before we ride on Rails, let us recapitulate a few points of Ruby, which is the base
of Rails.
Ruby is the successful combination of −

 Smalltalk's conceptual elegance,


 Python's ease of use and learning, and
 Perl's pragmatism.
Ruby is −

 A high-level programming language.


 Interpreted like Perl, Python, Tcl/TK.
 Object-oriented like Smalltalk, Eiffel, Ada, Java.
Why Ruby?
Ruby originated in Japan and now it is gaining popularity in US and Europe as
well. The following factors contribute towards its popularity −

 Easy to learn
 Open source (very liberal license)
 Rich libraries
 Very easy to extend
 Truly object-oriented
 Less coding with fewer bugs
v
 Helpful community
Although we have many reasons to use Ruby, there are a few drawbacks as well
that you may have to consider before implementing Ruby −
 Performance Issues − Although it rivals Perl and Python, it is still an
interpreted language and we cannot compare it with high-level
programming languages like C or C++.
 Threading model − Ruby does not use native threads. Ruby threads are
simulated in the VM rather than running as native OS threads.

What is Rails?
 An extremely productive web-application framework.

 Written in Ruby by David Heinemeier Hansson.


 You could develop a web application at least ten times faster with Rails than
you could with a typical Java framework.
 An open source Ruby framework for developing database-backed web
applications.
 Configure your code with Database Schema.
 No compilation phase required.
Full Stack Framework
 Includes everything needed to create a database-driven web application,
using the Model-View-Controller pattern.
 Being a full-stack framework means all the layers are built to work
seamlessly together with less code.
 Requires fewer lines of code than other frameworks.
Convention over Configuration
 Rails shuns configuration files in favor of conventions, reflection, and
dynamic runtime extensions.
 Your application code and your running database already contain everything
that Rails needs to know!
Rails Strengths
Rails is packed with features that make you more productive, with many of the
following features building on one other.

vi
Metaprogramming
Where other frameworks use extensive code generation from scratch, Rail
framework uses Metaprogramming techniques to write programs. Ruby is one of
the best languages for Metaprogramming, and Rails uses this capability well.
Rails also uses code generation but relies much more on Metaprogramming for
the heavy lifting.
Active Record
Rails introduces the Active Record framework, which saves objects into the
database. The Rails version of the Active Record discovers the columns in a
database schema and automatically attaches them to your domain objects using
metaprogramming.
Convention over configuration
Most web development frameworks for .NET or Java force you to write pages of
configuration code. If you follow the suggested naming conventions, Rails doesn't
need much configuration.
Scaffolding
You often create temporary code in the early stages of development to help get an
application up quickly and see how major components work together. Rails
automatically creates much of the scaffolding you'll need.
Built-in testing
Rails creates simple automated tests you can then extend. Rails also provides
supporting code called harnesses and fixtures that make test cases easier to write
and run. Ruby can then execute all your automated tests with the rake utility.
Three environments
Rails gives you three default environments: development, testing, and production.
Each behaves slightly differently, making your entire software development cycle
easier. For example, Rails creates a fresh copy of the Test database for each test
run.

Sample Ruby Code


Here is a sample Ruby code to print "Hello Ruby"

# The Hello Class

vii
class Hello

def initialize( name )


@name = name.capitalize
end

def salute
puts "Hello #{@name}!"
end

end

# Create a new object


h = Hello.new("Ruby")

# Output "Hello Ruby!"


h.salute
Output − This will produce the following result −
Hello Ruby!
Embedded Ruby
Ruby provides a program called ERB (Embedded Ruby), written by Seki
Masatoshi. ERB allows you to put Ruby codes inside an HTML file. ERB reads
along, word for word, and then at a certain point, when it encounters a Ruby code
embedded in the document, it starts executing the Ruby code.
You need to know only two things to prepare an ERB document −
 If you want some Ruby code executed, enclose it between <% and %>.

viii
 If you want the result of the code execution to be printed out, as a part of the
output, enclose the code between <%= and %>.
Here's an example. Save the code in erbdemo.rb file. Note that a Ruby file will
have an extension .rb −

<% page_title = "Demonstration of ERB" %>


<% salutation = "Dear programmer," %>

<html>

<head>
<title><%= page_title %></title>
</head>

<body>
<p><%= salutation %></p>
<p>This is an example of how ERB fills out a template.</p>
</body>

</html>
Now, run the program using the command-line utility erb.
tp> erb erbdemo.rb
This will produce the following result −

<html>

<head>
<title>Demonstration of ERb</title>
ix
</head>

<body>
<p>Dear programmer,</p>
<p>This is an example of how ERb fills out a template.</p>
</body>

</html>

IMPLEMENTATION
x
To develop a web application using Ruby on Rails Framework, we need to install
the following software −

 Ruby
 The Rails Framework
 A Web Server
 A Database System

Rails Installation on Windows


Follow the steps given below for installing Ruby on Rails.

xi
Step 1: Check Ruby Version
First, check if you already have Ruby installed. Open the command prompt and type ruby -v. If
Ruby responds, and if it shows a version number at or above 2.2.2, then type gem --version. If
you don't get an error, skip Install Ruby step. Otherwise, we'll install a fresh Ruby.

Step 2: Install Ruby


If Ruby is not installed, then download an installation package from rubyinstaller.org. Follow
the download link, and run the resulting installer. This is an exe file rubyinstaller-
2.2.2.x.exe and will be installed in a single click. It's a very small package, and you'll get
RubyGems as well along with this package. Please check the Release Notes for more detail.

Step 3: Install Rails


Install Rails − With Rubygems loaded, you can install all of Rails and its dependencies using
the following command through the command line −
C:\> gem install rails

Note − The above command may take some time to install all dependencies. Make sure you are
connected to the internet while installing gems dependencies.

Step 4: Check Rails Version


Use the following command to check the rails version.
C:\> rails -v

Output
Rails 4.2.4

xii
Congratulations! You are now on Rails over Windows.

Rails Installation on Linux


We are installing Ruby On Rails on Linux using rbenv. It is a lightweight Ruby Version
Management Tool. The rbenv provides an easy installation procedure to manage various
versions of Ruby, and a solid environment for developing Ruby on Rails applications.
Follow the steps given below to install Ruby on Rails using rbenv tool.

Step 1: Install Prerequisite Dependencies


First of all, we have to install git - core and some ruby dependences that help to install Ruby on
Rails. Use the following command for installing Rails dependencies using yum.
tp> sudo yum install -y git-core zlib zlib-devel gcc-c++ patch readline readline-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool
bison curl sqlite-devel

Step 2: Install rbenv


Now we will install rbenv and set the appropriate environment variables. Use the following set
of commands to get rbenv for git repository.
tp> git clone git://github.com/sstephenson/rbenv.git .rbenv
tp> echo 'export PATH = "$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile
tp> echo 'eval "$(rbenv init -)"' >> ~/.bash_profile
tp> exec $SHELL

tp> git clone git://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build


tp> echo 'export PATH = "$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' << ~/.bash_profile
tp> exec $SHELL

Step 3: Install Ruby


Before installing Ruby, determine which version of Ruby you want to install. We will install
Ruby 2.2.3. Use the following command for installing Ruby.
tp> rbenv install -v 2.2.3

Use the following command for setting up the current Ruby version as default.
tp> rbenv global 2.2.3

Use the following command to verify the Ruby version.


tp> ruby -v

Output
ruby 2.2.3p173 (2015-08-18 revivion 51636) [X86_64-linux]

Ruby provides a keyword gem for installing the supported dependencies; we call them gems. If
you don't want to install the documentation for Ruby-gems, then use the following command.
tp> echo "gem: --no-document" > ~/.gemrc

Thereafter, it is better to install the Bundler gem, because it helps to manage your application
dependencies. Use the following command to install bundler gem.
tp> gem install bundler

xiii
Step 4: Install Rails
Use the following command for installing Rails version 4.2.4.
tp> install rails -v 4.2.4

Use the following command to make Rails executable available.


tp> rbenv rehash

Use the following command for checking the rails version.


tp> rails -v

Output
tp> Rails 4.2.4

Ruby on Rails framework requires JavaScript Runtime Environment (Node.js) to manage the
features of Rails. Next, we will see how we can use Node.js to manage Asset Pipeline which is
a Rails feature.

Step 5: Install JavaScript Runtime


Let us install Node.js from the Yum repository. We will take Node.js from EPEL yum
repository. Use the following command to add the EPEL package to the yum repository.
tp> sudo yum -y install epel-release

Use the following command for installing the Node.js package.


tp> sudo yum install nodejs

Congratulations! You are now on Rails over Linux.

Step 6: Install Database


By default, Rails uses sqlite3, but you may want to install MySQL, PostgreSQL, or other
RDBMS. This is optional; if you have the database installed, then you may skip this step and it
is not mandatory that you have a database installed to start the rails server. For this tutorial, we
are using PostgreSQL database. Therefore use the following commands to install PostgreSQL.
tp> sudo yum install postgresql-server postgresql-contrib

Accept the prompt, by responding with a y. Use the following command to create a PostgreSQl
database cluster.
tp> sudo postgresql-setup initdb

Use the following command to start and enable PostgreSQL.


tp> sudo systemctl start postgresql
tp> sudo systemctl enable postgresql

Keeping Rails Up-to-Date


Assuming you have installed Rails using RubyGems, keeping it up-to-date is relatively easy.
We can use the same command in both Windows and Linux platform. Use the following
command −
tp> gem update rails

xiv
Output
The following screenshot shows a Windows command prompt. The Linux terminal also
provides the same output.

This will automatically update your Rails installation. The next time you restart your
application, it will pick up this latest version of Rails. While using this command, make sure
you are connected to the internet.

Installation Verification
You can verify if everything is set up according to your requirements or not. Use the following
command to create a demo project.
tp> rails new demo

Output

xv
It will generate a demo rail project; we will discuss about it later. Currently we have to check if
the environment is set up or not. Next, use the following command to run WEBrick web server
on your machine.
tp> cd demo
tp> rails server

It will generate auto-code to start the server

Now open your browser and type the following −


http://localhost:3000

It should display a message, something like, "Welcome aboard" or "Congratulations".


A framework is a program, set of programs, and/or code library that writes most of your
application for you. When you use a framework, your job is to write the parts of the application
that make it do the specific things you want.
When you set out to write a Rails application, leaving aside the configuration and other
housekeeping chores, you have to perform three primary tasks −
 Describe and model your application's domain − The domain is the universe of your
application. The domain may be a music store, a university, a dating service, an address
book, or a hardware inventory. So here you have to figure out what's in it, what entities

xvi
exist in this universe and how the items in it relate to each other. This is equivalent to
modeling a database structure to keep the entities and their relationship.
 Specify what can happen in this domain − The domain model is static; you have to
make it dynamic. Addresses can be added to an address book. Musical scores can be
purchased from music stores. Users can log in to a dating service. Students can register
for classes at a university. You need to identify all the possible scenarios or actions that
the elements of your domain can participate in.
 Choose and design the publicly available views of the domain − At this point, you can
start thinking in Web-browser terms. Once you've decided that your domain has
students, and that they can register for classes, you can envision a welcome page, a
registration page, and a confirmation page, etc. Each of these pages, or views, shows the
user how things stand at a certain point.
Based on the above three tasks, Ruby on Rails deals with a Model/View/Controller (MVC)
framework.

Ruby on Rails MVC Framework


The Model View Controller principle divides the work of an application into three separate but
closely cooperative subsystems.

Model (ActiveRecord )
It maintains the relationship between the objects and the database and handles validation,
association, transactions, and more.
This subsystem is implemented in ActiveRecord library, which provides an interface and
binding between the tables in a relational database and the Ruby program code that manipulates
database records. Ruby method names are automatically generated from the field names of
database tables.

View ( ActionView )
It is a presentation of data in a particular format, triggered by a controller's decision to present
the data. They are script-based template systems like JSP, ASP, PHP, and very easy to integrate
with AJAX technology.
This subsystem is implemented in ActionView library, which is an Embedded Ruby (ERb)
based system for defining presentation templates for data presentation. Every Web connection
to a Rails application results in the displaying of a view.

Controller ( ActionController )
The facility within the application that directs traffic, on the one hand, querying the models for
specific data, and on the other hand, organizing that data (searching, sorting, messaging it) into
a form that fits the needs of a given view.
This subsystem is implemented in ActionController, which is a data broker sitting between
ActiveRecord (the database interface) and ActionView (the presentation engine).

xvii
Pictorial Representation of MVC Framework
Given below is a pictorial representation of Ruby on Rails Framework −

Directory Representation of MVC Framework


Assuming a standard, default installation over Linux, you can find them like this −
tp> cd /usr/local/lib/ruby/gems/2.2.0/gems
tp> ls

You will see subdirectories including (but not limited to) the following −


actionpack-x.y.z
 activerecord-x.y.z
 rails-x.y.z
Over a windows installation, you can find them like this −
tp>cd ruby\lib\ruby\gems\2.2.0\gems
ruby\lib\ruby\gems\2.2.0\gems\>dir

You will see subdirectories including (but not limited to) the following −

xviii
ActionView and ActionController are bundled together under ActionPack.
ActiveRecord provides a range of programming techniques and shortcuts for manipulating data
from an SQL database. ActionController and ActionView provides facilities for manipulating
and displaying that data. Rails ties it all together.

xix
Sessions
To save data across multiple requests, you can use either the session or the flash hashes. A flash
stores a value (normally text) until the next request, while a session stores data during the
complete session.
session[:user] = @user

flash[:message] = "Data was saved successfully"

<%= link_to "login", :action => 'login' unless session[:user] %>

<% if flash[:message] %>

<div><%= h flash[:message] %></div>

<% end %>

It's possible to turn off session management −


session :off # turn session management off

session :off, :only => :action # only for this :action

session :off, :except => :action # except for this action

session :only => :foo, # only for :foo when doing HTTPS

:session_secure => true

session :off, :only=>:foo, # off for foo,if uses as Web Service

:if => Proc.new { |req| req.parameters[:ws] }

Check out link for more detail on Session Management

Cookies
Following is the syntax for setting cookies −
# Set a simple session cookie

cookies[:user_name] = "david"

# Set a cookie that expires in 1 hour

cookies[:login] = { :value => "XJ12", :expires => Time.now + 3600}

Following is the syntax for reading cookies −


cookies[:user_name] # => "david"

cookies.size # => 2

xx
Following is the syntax for deleting cookies −
cookies.delete :user_name

All the option symbols for setting cookies are −


 value − The cookie.s value or list of values (as an array).
 path − The path for which this cookie applies. Defaults to the root of the application.
 domain − The domain for which this cookie applies.
 expires − The time at which this cookie expires, as a +Time+ object.
 secure − Whether this cookie is a secure cookie or not (default to false). Secure cookies
are only transmitted to HTTPS servers.

During the life cycle of an active record object, you can hook into 8
events −
 (-) save
 (-) valid?
 before_validation
 before_validation_on_create
 (-) validate
 (-) validate_on_create
 after_validation
 after_validation_on_create
 before_save
 before_create
 (-) create
 after_create
 after_save

xxi
Examples
class Subscription < ActiveRecord::Base

before_create :record_signup

private

def record_signup

self.signed_up_on = Date.today

end

end

class Firm < ActiveRecord::Base

# Destroys the associated clients and

# people when the firm is destroyed

before_destroy{

|record|Person.destroy_all "firm_id= #{record.id}"

before_destroy{

|record|Client.destroy_all "client_of= #{record.id}"

end

This examples shows how we can nest with_scope to fetch different results based on
requirements.
# SELECT * FROM employees

# WHERE (salary > 10000)

# LIMIT 10

# Will be written as

Employee.with_scope(

:find => { :conditions => "salary > 10000",

:limit => 10 }) do

Employee.find(:all)

xxii
end

Now, check another example how scope is cumulative.


# SELECT * FROM employees

# WHERE ( salary > 10000 )

# AND ( name = 'Jamis' ))

# LIMIT 10

# Will be written as

Employee.with_scope(

:find => { :conditions => "salary > 10000", :limit => 10 }) do

Employee.find(:all)

Employee.with_scope(:find => { :conditions => "name = 'Jamis'" }) do

Employee.find(:all)

end

end

One more example which shows how previous scope is ignored.


# SELECT * FROM employees

# WHERE (name = 'Jamis')

# is written as

Employee.with_scope(

:find => { :conditions => "salary > 10000", :limit => 10 }) do

Employee.find(:all)

Employee.with_scope(:find => { :conditions => "name = 'Jamis'" }) do

Employee.find(:all)

end

# all previous scope is ignored

Employee.with_exclusive_scope(:find => { :conditions => "name = 'Jamis'" }) do

Employee.find(:all)

end

end

xxiii
Following are the ways to find out records with and without conditions −
The following will find an author with ID 50.
Author.find(50)

The following will find authors with ID 20, 30 and 40.


Author.find([20,30, 40])

The following will find all the authors −


Author.find :all

The following will find all the authors with first name alam.
Author.find :all

:condition => ["first_name =?", "alam" ]

The following will find the first record of the authors with first name alam.
Author.find :first

:condition => ["first_name =?", "alam" ]

Options for Finders


You can use following option along with find function.
 :order => 'name DESC' Use this option to sort the result in ascending or descending
order.
 :offset => 20 Starts fetching records from offset 20.
 :limit => 20 Returns only 20 records.
 :group => 'name' This is equivalent to sql fragment GROUP BY.
 :joins => LEFT JOIN ...' Additional LEFT JOIN (rarely used).
 :include => [:account, :friends] This is LEFT OUTER JOIN with these model.
 :select => [:name, :address] Use this instead of SELECT * FROM.
 :readonly => true Use this to make objects write protected.

Dynamic attribute-based Finders


You can use more dynamic functions to fetch values.
If there is a field user_name, then you can use the following to find records by user name.
Person.find_by_user_name(user_name)

If there is a field last_name, then you can use the following to find records by last name.
Person.find_all_by_last_name(last_name)

xxiv
If there are fields user_name and password, then you can use the following to find a record for
a given user name and password.
Person.find_by_user_name_and_password(user_name, password)

Ruby provides many useful scripts, which you use during your project implementation. Here are
few scripts which you will use most frequently.

Script Description

script/about Gives information about environment.

script/breakpointer Starts the breakpoint server.

script/console Interactive Rails Console.

script/destroy Deletes files created by generators.

script/generate Used by generators.

script/runner Executes a task in the rails context.

script/server Launches the development server.

script/performance/profile Profiles an expansive method.

script/performance/benchmarker Benchmarks different methods.

Script Example
Here is an example to call a script. Following script will start development server.
C:\ruby> ruby script/server

Ruby provides many useful scripts, which you use during your project implementation. Here are
few scripts which you will use most frequently.

Script Description

script/about Gives information about environment.

xxv
script/breakpointer Starts the breakpoint server.

script/console Interactive Rails Console.

script/destroy Deletes files created by generators.

script/generate Used by generators.

script/runner Executes a task in the rails context.

script/server Launches the development server.

script/performance/profile Profiles an expansive method.

script/performance/benchmarker Benchmarks different methods.

Script Example
Here is an example to call a script. Following script will start development server.
C:\ruby> ruby script/server

Ruby provides a script called Generator. This script can be used to generate many useful items
in Rails. Most important generators are listed below.

Generator Description

script/generate model ModellName Generates Active


Records.

script/generate controller ListController Generates Controller.


show edit

script/generate scaffold ModelName Generates Scaffold.


ControllerName

script/generate migration AddNewTable Generates Table to


migrate.

xxvi
script/generate plugin PluginName Generates Plugin.

script/generate integration_test TestName Generates Integ Test.

script/generate session_migration Generates Session


Migration.

Following is the list of options, which can be used along with generators −
 -p, --pretend Run but do not make any changes.
 -f, --force Overwrite files that already exist.
 -s, --skip Skip files that already exist.
 -q, --quite Suppress normal output.
 -t, --backtrace Debugging: show backtrace on errors.
 -h, --help Show this help message.
 -c, --svn Modify files with subversion.

xxvii
AngularJS
What is AngularJS?
AngularJS is an open source web application framework. It was originally developed in 2009 by
Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.4.3.
Definition of AngularJS as put by its official documentation is as follows −
AngularJS is a structural framework for dynamic web apps. It lets you use HTML as your template
language and lets you extend HTML's syntax to express your application's components clearly and
succinctly. Angular's data binding and dependency injection eliminate much of the code you currently
have to write. And it all happens within the browser, making it an ideal partner with any server
technology.

Features
 AngularJS is a powerful JavaScript based development framework to create RICH
Internet Application(RIA).
 AngularJS provides developers options to write client side application (using JavaScript)
in a clean MVC(Model View Controller) way.
 Application written in AngularJS is cross-browser compliant. AngularJS automatically
handles JavaScript code suitable for each browser.
 AngularJS is open source, completely free, and used by thousands of developers around
the world. It is licensed under the Apache License version 2.0.
Overall, AngularJS is a framework to build large scale and high performance web application
while keeping them as easy-to-maintain.

Core Features
Following are most important core features of AngularJS −
 Data-binding − It is the automatic synchronization of data between model and view
components.
 Scope − These are objects that refer to the model. They act as a glue between controller
and view.
 Controller − These are JavaScript functions that are bound to a particular scope.
 Services − AngularJS come with several built-in services for example $https: to make a
XMLHttpRequests. These are singleton objects which are instantiated only once in app.
 Filters − These select a subset of items from an array and returns a new array.

xxviii
 Directives − Directives are markers on DOM elements (such as elements, attributes, css,
and more). These can be used to create custom HTML tags that serve as new, custom
widgets. AngularJS has built-in directives (ngBind, ngModel...)
 Templates − These are the rendered view with information from the controller and
model. These can be a single file (like index.html) or multiple views in one page using
"partials".
 Routing − It is concept of switching views.
 Model View Whatever − MVC is a design pattern for dividing an application into
different parts (called Model, View and Controller), each with distinct responsibilities.
AngularJS does not implement MVC in the traditional sense, but rather something closer
to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as
Model View Whatever.
 Deep Linking − Deep linking allows you to encode the state of application in the URL
so that it can be bookmarked. The application can then be restored from the URL to the
same state.
 Dependency Injection − AngularJS has a built-in dependency injection subsystem that
helps the developer by making the application easier to develop, understand, and test.

xxix
Concepts
Following diagram depicts some important parts of AngularJS which we will discuss in detail in
the subsequent chapters.

Advantages of AngularJS
 AngularJS provides capability to create Single Page Application in a very clean and
maintainable way.
 AngularJS provides data binding capability to HTML thus giving user a rich and
responsive experience
 AngularJS code is unit testable.
 AngularJS uses dependency injection and make use of separation of concerns.
 AngularJS provides reusable components.
 With AngularJS, developer write less code and get more functionality.

xxx
 In AngularJS, views are pure html pages, and controllers written in JavaScript do the
business processing.
On top of everything, AngularJS applications can run on all major browsers and smart phones
including Android and iOS based phones/tablets.

Disadvantages of AngularJS
Though AngularJS comes with lots of plus points but same time we should consider the
following points −
 Not Secure − Being JavaScript only framework, application written in AngularJS are not
safe. Server side authentication and authorization is must to keep an application secure.
 Not degradable − If your application user disables JavaScript then user will just see the
basic page and nothing more.

The AngularJS Components


The AngularJS framework can be divided into following three major parts −
 ng-app − This directive defines and links an AngularJS application to HTML.
 ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
 ng-bind − This directive binds the AngularJS Application data to HTML tags.
Model View Controller or MVC as it is popularly called, is a software design pattern for
developing web applications. A Model View Controller pattern is made up of the following
three parts −
 Model − It is the lowest level of the pattern responsible for maintaining data.
 View − It is responsible for displaying all or a portion of the data to the user.
 Controller − It is a software Code that controls the interactions between the Model and
View.
MVC is popular because it isolates the application logic from the user interface layer and
supports separation of concerns. The controller receives all requests for the application and then
works with the model to prepare any data needed by the view. The view then uses the data
prepared by the controller to generate a final presentable response. The MVC abstraction can be
graphically represented as follows.

xxxi
The Model
The model is responsible for managing application data. It responds to the request from view
and to the instructions from controller to update itself.

The View
A presentation of data in a particular format, triggered by the controller's decision to present the
data. They are script-based template systems such as JSP, ASP, PHP and very easy to integrate
with AJAX technology.

The Controller
The controller responds to user input and performs interactions on the data model objects. The
controller receives input, validates it, and then performs business operations that modify the
state of the data model.
AngularJS is a MVC based framework. In the coming chapters, we will see how AngularJS uses
MVC methodology.
AngularJS directives are used to extend HTML. These are special attributes starting with ng-
prefix. We're going to discuss following directives −

xxxii
 ng-app − This directive starts an AngularJS Application.
 ng-init − This directive initializes application data.
 ng-model − This directive binds the values of AngularJS application data to HTML
input controls.
 ng-repeat − This directive repeats html elements for each item in a collection.

ng-app directive
ng-app directive starts an AngularJS Application. It defines the root element. It automatically
initializes or bootstraps the application when web page containing AngularJS Application is
loaded. It is also used to load various AngularJS modules in AngularJS Application. In
following example, we've defined a default AngularJS application using ng-app attribute of a
div element.
<div ng-app = "">

...

</div>

ng-init directive
ng-init directive initializes an AngularJS Application data. It is used to put values to the
variables to be used in the application. In following example, we'll initialize an array of
countries. We're using JSON syntax to define array of countries.
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-
FR',name:'France'}]">

...

</div>

ng-model directive
This directive binds the values of AngularJS application data to HTML input controls. In
following example, we've defined a model named "name".
<div ng-app = "">

...

<p>Enter your Name: <input type = "text" ng-model = "name"></p>

</div>

ng-repeat directive
ng-repeat directive repeats html elements for each item in a collection. In following example,
we've iterated over array of countries.
<div ng-app = "">

xxxiii
...

<p>List of Countries with locale:</p>

<ol>

<li ng-repeat = "country in countries">

{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}

</li>

</ol>

</div>

Example
Following example will showcase all the above mentioned directives.
testAngularJS.htm
<html>

<head>

<title>AngularJS Directives</title>

</head>

<body>

<h1>Sample Application</h1>

<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-
FR',name:'France'}]">

<p>Enter your Name: <input type = "text" ng-model = "name"></p>

<p>Hello <span ng-bind = "name"></span>!</p>

<p>List of Countries with locale:</p>

<ol>

<li ng-repeat = "country in countries">

{{ 'Country: ' + country.name + ', Locale: ' + country.locale }}

</li>

</ol>

</div>

xxxiv
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</body>

</html>

Output
Open textAngularJS.htm in a web browser. Enter your name and see the result.
Expressions are used to bind application data to html. Expressions are written inside double
braces like {{ expression}}. Expressions behaves in same way as ng-bind directives. AngularJS
application expressions are pure javascript expressions and outputs the data where they are
used.

Using numbers
<p>Expense on Books : {{cost * quantity}} Rs</p>

Using strings
<p>Hello {{student.firstname + " " + student.lastname}}!</p>

Using object
<p>Roll No: {{student.rollno}}</p>

Using array
<p>Marks(Math): {{marks[3]}}</p>

Example
Following example will showcase all the above mentioned expressions.
testAngularJS.htm
<html>

<head>

<title>AngularJS Expressions</title>

</head>

<body>

<h1>Sample Application</h1>

xxxv
<div ng-app = "" ng-init = "quantity = 1;cost = 30; student = {firstname:'Mahesh',lastname:'Parashar',rollno:101};marks = [80,90,75,73,60]">

<p>Hello {{student.firstname + " " + student.lastname}}!</p>

<p>Expense on Books : {{cost * quantity}} Rs</p>

<p>Roll No: {{student.rollno}}</p>

<p>Marks(Math): {{marks[3]}}</p>

</div>

<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</body>

</html>

Output
Open textAngularJS.htm in a web browser. See the result.

Scope
xxxvi
Even with traditional, multi-page sites, having solutions that make development
and testing of those sites quicker and easier is always going to be welcome and
appealing.

AngularJS already has the ability to handle your project’s wireframes during initial
development and testing, as well as other demands like animations and transitions
for powerful websites and web applications. With more and more web designers
and developers turning to these JavaScript-powered solutions, we can also expect
them to become even easier to use as a whole – which is ultimately great news for
everyone looking to design and develop rich web experiences.

CONCLUSION & FUTURE ENHANCEMENT


xxxvii
CONCLUSION
It has been a matter of immense pleasure, honour and challenges to have this
opportunity to take up this project and complete it successfully.
While developing this project I have learnt a lot about web development using
angular js and ruby on rails, I have also learnt how to make it user friendly (easy to
make use and handle) by hiding the complicated parts of it from the users.
During the development process I studied carefully and understood the criteria for
making a software more demanding, I also realized the importance of maintaining
a minimal margin for error.

FUTURE ENHANCEMENT
In future our report could help others to easily develop websites using ruby on rails
and angular js.

xxxviii

You might also like