0% found this document useful (0 votes)
1 views

Module-6-MVC, Angular JS (5)

The document provides an overview of MVC architecture and its application in web and mobile development, emphasizing the separation of business logic and presentation. It introduces JavaScript frameworks, particularly AngularJS, detailing its features such as directives, modules, and controllers, which facilitate the development of dynamic web applications. Additionally, it explains how AngularJS extends HTML and utilizes expressions for data binding and interaction within applications.

Uploaded by

Viriyala Manasa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Module-6-MVC, Angular JS (5)

The document provides an overview of MVC architecture and its application in web and mobile development, emphasizing the separation of business logic and presentation. It introduces JavaScript frameworks, particularly AngularJS, detailing its features such as directives, modules, and controllers, which facilitate the development of dynamic web applications. Additionally, it explains how AngularJS extends HTML and utilizes expressions for data binding and interaction within applications.

Uploaded by

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

Advanced

Technologies
MVC Architecture:

• The MVC framework is an architectural pattern that separates an application into three main logical components
Model, View, and Controller

• MVC separates the business logic and presentation layer from each other

• It was traditionally used for desktop graphical user interfaces (GUIs)

• Nowadays, MVC architecture in web technology has become popular for designing
 Web applications
 Mobile apps

• Three important MVC components are:


Model: It includes all the data and its related logic
View: Present data to the user or handles user interaction
Controller: An interface between Model and View components
Introduction to JS frameworks:

• A JS framework is a collection of JavaScript code libraries that provide developers with pre-written code for routine
programming tasks

• Each time you have to build an application, you don’t need to write code for every single feature from scratch

• Instead, you can build upon an existing feature set

• JS frameworks provide some rules and guidelines

• Using these rules and guidelines, any developer can make complex applications faster and more efficiently

Framework Vs. Library

Framework Library
It is a full toolkit Collection of pre-written code snippets
Shape and organize your website or application Less about shaping your application and more about
providing a use-as-needed library of features
Angular JS
• AngularJS is a JavaScript framework

• It is perfect for Single Page Applications (SPAs)

• AngularJS extends HTML with new attributes

• AngularJS is distributed as a JavaScript file, and can be added to a web page with a script tag:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
Angular JS Extends HTML:

• AngularJS extends HTML with ng-directives

• The ng-app directive defines an Angular JS application

• The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.

• The ng-bind directive binds application data to the HTML view.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>
AngularJS starts automatically when the web page has loaded.

The ng-app directive tells AngularJS that the <div> element is the "owner" of AngularJS application.

The ng-model directive binds the value of the input field to the application variable name.

The ng-bind directive binds the content of the <p> element to the application variable name.

AngularJS Expressions
AngularJS expressions can be written inside double braces: {{ expression }}.

AngularJS expressions can also be written inside a directive: ng-bind="expression".

AngularJS will resolve the expression, and return the result exactly where the expression is written.

AngularJS expressions are much like JavaScript expressions: They can contain literals, operators, and variables.

Example {{ 5 + 5 }} or {{ firstName + " " + lastName }}


<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app=“”>
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>

Example: Change the color of the input box by changing its value:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<p>Change the value of the input field:</p>
<div ng-app="" ng-init="myColor='lightblue'">
<input style="background-color:{{myColor}}" ng-model="myColor">
</div>
</body>
</html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>
</body>
</html>

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: <span ng-bind="quantity * cost"></span></p>
</div>
</body>
</html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="firstName='John';lastName='Doe’”>
<p>The full name is: {{ firstName + " " + lastName }}</p>
</div>
</body>
</html>

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="firstName='John';lastName='Doe’”>
<p>The full name is: <span ng-bind="firstName + ' ' + lastName"></span></p>
</div>
</body>
</html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>
</div>
</body>
</html>

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is <span ng-bind="person.lastName"></span></p>
</div>
</body>
</html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
</div>
</body>
</html>

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is <span ng-bind="points[2]"></span></p>
</div>
</body>
</html>
AngularJS Modules
An AngularJS module defines an application.

The module is a container for the different parts of an application.

Creating a Module

A module is created by using the AngularJS function angular.module

<div ng-app="myApp">...</div>
<script>
var app = angular.module("myApp", []);
</script>

The "myApp" parameter refers to an HTML element in which the application will run.

Now you can add controllers, directives, filters, and more, to your AngularJS application.
Adding a Controller

Add a controller to your application, and refer to the controller with the ng-controller directive:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApplication" ng-controller="myController">
{{ firstName + " " + lastName }}
</div>
<script>
var app = angular.module(" myApplication", []);
app.controller("myController", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
Modules and Controllers in Files

It is common in AngularJS applications to put the module and the controllers in JavaScript files.

In this example, "myApp.js" contains an application module definition, while "myCtrl.js" contains the controller:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApplication" ng-controller="myController">
{{ firstName + " " + lastName }}
</div>

<script src="myApp.js"></script>
<script src="myCtrl.js"></script>
</body>
</html>
myApp.js

var app = angular.module("myApplication", []);

The [] parameter in the module definition can be used to define dependent modules.

Without the [] parameter, you are not creating a new module, but retrieving an existing one.

myCtrl.js

app.controller("myController", function($scope) {
$scope.firstName = "John";
$scope.lastName= "Doe";
});

When to Load the Library

While it is common in HTML applications to place scripts at the end of the <body> element, it is recommended that you
load the AngularJS library either in the <head> or at the start of the <body>.

This is because calls to angular.module can only be compiled after the library has been loaded.
AngularJS Directives
The ng-repeat directive repeats an HTML element:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="names=['Jani','Hege','Kai']">
<ul>
<li ng-repeat="x in names">
{{ x }}
</li>
</ul>
</div>
</body>
</html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="" ng-init="names=[{name:'Jani',country:'Norway'},{name:'Hege',country:'Sweden’},
{name:'Kai',country:'Denmark'}]">
<ul>
<li ng-repeat="x in names">
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
</body>
</html>
Create New Directives

In addition to all the built-in AngularJS directives, you can create your own directives.

New directives are created by using the .directive function.

To invoke the new directive, make an HTML element with the same tag name as the new directive.

When naming a directive, you must use a camel case name, w3TestDirective, but when invoking it, you must
use - separated name, w3-test-directive:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApplication">
<w3-test-directive></w3-test-directive>
<script>
var app = angular.module("myApplication", []);
app.directive("w3TestDirective", function() {
return
{
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
</html>
You can invoke a directive by using:
• Element name
• Attribute
• Class
• Comment

The examples below will all produce the same result:

Element name
<w3-test-directive></w3-test-directive>

Attribute
<div w3-test-directive></div>

Class
<div class="w3-test-directive"></div>

Comment
<!-- directive: w3-test-directive -->
Restrictions

You can restrict your directives to only be invoked by some of the methods.

By adding a restrict property with the value "A", the directive can only be invoked by attributes:

The legal restrict values are:

• E for Element name


• A for Attribute
• C for Class
• M for Comment

By default the value is EA, meaning that both Element names and attribute names can invoke the directive.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApplication">
<w3-test-directive></w3-test-directive>
<div w3-test-directive></div>
<script>
var app = angular.module("myApplication", []);
app.directive("w3TestDirective", function() {
return
{
restrict : "A",
template : "<h1>Made by a directive!</h1>"
};
});
</script>
</body>
</html>
AngularJS Controllers
AngularJS applications are controlled by controllers.

The ng-controller directive defines the application controller.

A controller is a JavaScript Object, created by a standard JavaScript object constructor.


<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>
</body>
</html>
The AngularJS application is defined by ng-app="myApp".

The application runs inside the <div>.

The ng-controller="myCtrl" attribute defines a controller.

The myCtrl function is a JavaScript function.

AngularJS will invoke the controller with a $scope object.

In AngularJS, $scope is the application object (the owner of application variables and functions).

The controller creates two properties (variables) in the scope (firstName and lastName).

The ng-model directives bind the input fields to the controller properties (firstName and lastName).
A controller can also have methods (variables as functions):

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
$scope.fullName = function() {
return $scope.firstName + " " + $scope.lastName;
};
});
</script>
</body>
</html>
Controllers In External Files

In larger applications, it is common to store controllers in external files.

Just copy the code between the <script> tags into an external file named personController.js:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{fullName()}}
</div>
<script src="personController.js"></script>
</body>
</html>
AngularJS Scope

The scope is an object with the available properties and methods.

The scope is available for both the view and the controller.

When you make a controller in AngularJS, you pass the $scope object as an argument:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{carname}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.carname = "Volvo";
});
</script>
</body>
</html>
If we consider an AngularJS application to consist of:

• View, which is the HTML.

• Model, which is the data available for the current view.

• Controller, which is the JavaScript function that makes/changes/removes/controls the data.

Then the scope is the Model.

If you make changes in the view, the model and the controller will be updated.

Root Scope

All applications have a $rootScope which is the scope created on the HTML element that contains the ng-app directive.

The rootScope is available in the entire application.

If a variable has the same name in both the current scope and in the rootScope, the application uses the one in the current
scope.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
<p>The rootScope's favorite color:</p>
<h1>{{color}}</h1>
<div ng-controller="myCtrl">
<p>The scope of the controller's favorite color:</p>
<h1>{{color}}</h1>
</div>
<p>The rootScope's favorite color is still:</p>
<h1>{{color}}</h1>
<script>
var app = angular.module('myApp', []);
app.run(function($rootScope) {
$rootScope.color = 'blue’;
});
app.controller('myCtrl', function($scope) {
$scope.color = "red";
});
</script>
</body>
</html>
AngularJS Filters

AngularJS provides filters to transform data:

• currency Format a number to a currency format.


• date Format a date to a specified format.
• filter Select a subset of items from an array.
• json Format an object to a JSON string.
• limitTo Limits an array/string, into a specified number of elements/characters.
• lowercase Format a string to lower case.
• number Format a number to a string.
• orderBy Orders an array by an expression.
• uppercase Format a string to upper case.

Filters can be added to expressions by using the pipe character |, followed by a filter.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="personCtrl">
<p>The name is {{ lastName | uppercase }}</p>
</div>
<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
});
</script>
</body>
</html>
Adding Filters to Directives

Filters are added to directives, like ng-repeat, by using the pipe character |, followed by a filter:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Looping with objects:</p>
<ul>
<li ng-repeat="x in names | orderBy:'country’”>
{{ x.name + ', ' + x.country }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England’},
{name:'Hege',country:'Norway’},
{name:'Joe',country:'Denmark’},
{name:'Gustav',country:'Sweden’},
];
});
</script>
</body>
</html>
The filter Filter

The filter filter selects a subset of an array.

The filter filter can only be used on arrays, and it returns an array containing only the matching items.

This example displays only the names containing the letter "i".

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<ul>
<li ng-repeat="x in names | filter : 'i’”>
{{ x }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [ 'Jani', 'Carl', 'Margareth', 'Hege', 'Joe', 'Gustav',
'Birgit’, 'Mary', 'Kai' ];
});
</script>
</body>
</html>

Filter an Array Based on User Input

By setting the ng-model directive on an input field, we can use the value of the input field as an expression in a filter.

Type a letter in the input field, and the list will shrink/grow depending on the match:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="namesCtrl">
<p>Type a letter in the input field:</p>
<p><input type="text" ng-model="test"></p>
<ul>
<li ng-repeat="x in names | filter:test">
{{ x }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = ['Jani','Carl','Margareth','Hege','Joe','Gustav','Birgit','Mary','Kai’];
});
</script>
</body>
</html>
Sort an Array Based on User Input

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<p>Click the table headers to change the sorting order:</p>
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width=“50%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [ {name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden’},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
}
});
</script>
</body>
</html>
Custom Filters

You can make your own filters by registering a new filter factory function with your module:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<ul ng-app="myApp" ng-controller="namesCtrl">
<li ng-repeat="x in names">
{{x | myFormat}}
</li>
</ul>
<script>
var app = angular.module('myApp', []);
app.filter('myFormat', function() {
return function(x) {
var i, c, txt = "";
for (i = 0; i < x.length; i++) {
c = x[i];
if (i % 2 == 0) {
c = c.toUpperCase();
}
txt += c;
}
return txt;
};
});
app.controller('namesCtrl', function($scope) {
$scope.names = ['Jani','Carl','Margareth','Hege','Joe','Gustav','Birgit','Mary','Kai’];
});
</script>
<</body>
</html>
AngularJS Services
In AngularJS, a service is an object, that is available for, and limited to, your AngularJS application.

AngularJS has about 30 built-in services.

The $http Service

The $http service is one of the most common used services in AngularJS applications. The service makes a request to the
server, and lets your application handle the response.

<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{myWelcome}}</h1>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm").then(function (response) {
$scope.myWelcome = response.data;
});
});
</script>
</body>
The $timeout Service

The $timeout service is AngularJS' version of the window.setTimeout function.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{myHeader}}</h1>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope, $timeout) {
$scope.myHeader = "Hello World!";
$timeout(function () {
$scope.myHeader = "How are you today?";
}, 2000);
});
</script>
</body>
</html>
The $interval Service

The $interval service is AngularJS' version of the window.setInterval function.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{theTime}}</h1>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope, $interval) {
$scope.theTime = new Date().toLocaleTimeString();
$interval(function () {
$scope.theTime = new Date().toLocaleTimeString();
}, 1000);
});
</script>
</body>
</html>
Create Your Own Service

To create your own service, connect your service to the module:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{hex}}</h1>
</div>
<script>
var app = angular.module('myApp', []);
app.service('hexafy', function() {
this.myFunc = function (x) {
return x.toString(16);
}
});
app.controller('myCtrl', function($scope, hexafy) {
$scope.hex = hexafy.myFunc(255);
});
</script>
</body>
</html>
AngularJS $http

The AngularJS $http service makes a request to the server, and returns a response.

Methods

The example above uses the .get method of the $http service.

The .get method is a shortcut method of the $http service. There are several shortcut methods:

•.delete()
•.get()
•.head()
•.jsonp()
•.patch()
•.post()
•.put()

The methods above are all shortcuts of calling the $http service:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1>{{myWelcome}}</h1>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope, $http) {
$http({
method : "GET",
url : "welcome.htm"
}).then(function mySuccess(response) {
$scope.myWelcome = response.data;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
});
</script>
</body>
</html>
Properties

The response from the server is an object with these properties:

•.config the object used to generate the request.


•.data a string, or an object, carrying the response from the server.
•.headers a function to use to get header information.
•.status a number defining the HTTP status.
•.statusText a string defining the HTTP status.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Data : {{content}}</p>
<p>Status : {{statuscode}}</p>
<p>StatusText : {{statustext}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("welcome.htm")
.then(function(response) {
$scope.content = response.data;
$scope.statuscode = response.status;
$scope.statustext = response.statusText;
});
});
</script>
</body>
</html>
JSON

The data you get from the response is expected to be in JSON format.

JSON is a great way of transporting data, and it is easy to use within AngularJS, or any other JavaScript.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<ul>
<li ng-repeat="x in myData">
{{ x.Name + ', ' + x.Country }}
</li>
</ul>
</div>
<script>
angular.module('myApp', []).controller('customersCtrl', function($scope, $http) {
$http.get("customers.php").then(function (response) {
$scope.myData = response.data.records;
});
});
</script>
</body>
</html>

customers.php

{ "records": [ { "Name": "Alfreds Futterkiste", "City": "Berlin", "Country": "Germany" }, { "Name": "Ana Trujillo
Emparedados y helados", "City": "México D.F.", "Country": "Mexico" }, { "Name": "Antonio Moreno Taquería", "City":
"México D.F.", "Country": "Mexico" }, { "Name": "Around the Horn", "City": "London", "Country": "UK" }, { "Name":
"B's Beverages", "City": "London", "Country": "UK" }, { "Name": "Berglunds snabbköp", "City": "Luleå", "Country":
"Sweden" }, { "Name": "Blauer See Delikatessen", "City": "Mannheim", "Country": "Germany" }, { "Name": "Blondel
père et fils", "City": "Strasbourg", "Country": "France" }, { "Name": "Bólido Comidas preparadas", "City": "Madrid",
"Country": "Spain" }, { "Name": "Bon app'", "City": "Marseille", "Country": "France" }, { "Name": "Bottom-Dollar
Marketse", "City": "Tsawassen", "Country": "Canada" }, { "Name": "Cactus Comidas para llevar", "City": "Buenos Aires",
"Country": "Argentina" }, { "Name": "Centro comercial Moctezuma", "City": "México D.F.", "Country": "Mexico" },
{ "Name": "Chop-suey Chinese", "City": "Bern", "Country": "Switzerland" }, { "Name": "Comércio Mineiro", "City": "São
Paulo", "Country": "Brazil" } ] }
AngularJS Tables
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table border=“1”>
<tr ng-repeat="x in names">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('customersCtrl', function($scope, $http) {
$http.get("customers.php")
.then(function (response) {
$scope.names = response.data.records;
});
});
</script>
</body>
</html>
To sort the table, add an orderBy filter:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table border=“1”>
<tr ng-repeat="x in names | orderBy : 'Country’ ">
<td>{{ x.Name }}</td>
<td>{{ x.Country }}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('customersCtrl', function($scope, $http) {
$http.get("customers.php")
.then(function (response) {
$scope.names = response.data.records;
});
});
</script>
</body>
</html>
Using $even and $odd

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="customersCtrl">
<table border=“1”>
<tr ng-repeat="x in names">
<td ng-if="$odd" style="background-color:#f1f1f1">
{{ x.Name }}
</td>
<td ng-if="$even">
{{ x.Name }}
</td>
<td ng-if="$odd" style="background-color:#f1f1f1">
{{ x.Country }}
</td>
<td ng-if="$even">
{{ x.Country }}
</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('customersCtrl', function($scope, $http) {
$http.get("customers.php")
.then(function (response) {
$scope.names = response.data.records;
});
});
</script>
</body>
</html>
AngularJS Select Boxes

AngularJS lets you create dropdown lists based on items in an array, or an object.

If you want to create a dropdown list, based on an object or an array in AngularJS, you should use the ng-options directive:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names"></select>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.names = ["Emil", "Tobias", "Linus"];
});
</script>
</body>
</html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Select a car:</p>
<select ng-model="selectedCar">
<option ng-repeat="x in cars">{{x.model}}</option>
</select>
<h1>You selected: {{selectedCar}}</h1>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.cars = [
{model : "Ford Mustang", color : "red"},
{model : "Fiat 500", color : "white"},
{model : "Volvo XC90", color : "black"}
];
});s
</script>
</body>
</html>
When using the value as an object, use ng-value insead of value

<div ng-app="myApp" ng-controller="myCtrl">


<p>Select a car:</p>
<select ng-model="selectedCar">
<option ng-repeat="x in cars" ng-value="{{x}}">{{x.model}}</option>
</select>
<h1>You selected a {{selectedCar.color}} {{selectedCar.model}}</h1>
</div>

<script>
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.cars = [
{model : "Ford Mustang", color : "red"},
{model : "Fiat 500", color : "white"},
{model : "Volvo XC90", color : "black"}
];
});
</script>
In the previous examples the data source was an array, but we can also use an object.

Assume you have an object with key-value pairs:

$scope.cars = {
car01 : "Ford",
car02 : "Fiat",
car03 : "Volvo"
};

Using an object as the data source, x represents the key, and y represents the value:

<select ng-model="selectedCar" ng-options="x for (x, y) in cars">


</select>

<h1>You selected: {{selectedCar}}</h1>


The options in the dropdown list does not have to be the key in a key-value pair, it can also be the value, or a property of the
value object:

<div ng-app="myApp" ng-controller="myCtrl">


<p>Select a car:</p>
<select ng-model="selectedCar" ng-options="y.brand for (x, y) in cars">
</select>
<h1>You selected: {{selectedCar.brand}}</h1>
<h2>Model: {{selectedCar.model}}</h2>
<h3>Color: {{selectedCar.color}}</h3>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.cars = {
car01 : {brand : "Ford", model : "Mustang", color : "red"},
car02 : {brand : "Fiat", model : "500", color : "white"},
car03 : {brand : "Volvo", model : "XC90", color : "black"}
}
});
</script>
AngularJS Events
You can add AngularJS event listeners to your HTML elements by using one or more of these directives:

•ng-blur
•ng-change
•ng-click
•ng-copy
•ng-cut
•ng-dblclick
•ng-focus
•ng-keydown
•ng-keypress
•ng-keyup
•ng-mousedown
•ng-mouseenter
•ng-mouseleave
•ng-mousemove
•ng-mouseover
•ng-mouseup
•ng-paste
The event directives allows us to run AngularJS functions at certain user events.

An AngularJS event will not overwrite an HTML event, both events will be executed.

Mouse Events

Mouse events occur when the cursor moves over an element, in this order:
1.ng-mouseover
2.ng-mouseenter
3.ng-mousemove
4.ng-mouseleave

Or when a mouse button is clicked on an element, in this order:


5.ng-mousedown
6.ng-mouseup
7.ng-click

You can add mouse events on any HTML element.


Example: Increase the count variable when the mouse moves over the H1 element:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<h1 ng-mousemove="count = count + 1">Mouse Over Me!</h1>
<h2>{{ count }}</h2>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
</body>
</html>
The ng-click Directive

The ng-click directive defines AngularJS code that will be executed when the element is being clicked.

Example

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="count = count + 1">Click Me!</button>
<p>{{ count }}</p>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.count = 0;
});
</script>
</body>
</html>
You can also refer to a function:

<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="myFunction()">Click Me!</button>
<p>{{ count }}</p>
</div>
<script>
angular.module('myApp', []).controller('myCtrl', function($scope) {
$scope.count = 0;
$scope.myFunction = function() {
$scope.count++;
}
});
</script>
</body>
</html>
AngularJS Forms

Forms in AngularJS provides data-binding and validation of input controls.

Input controls are the HTML input elements:


• input elements
• select elements
• button elements
• textarea elements

Data-Binding

Input controls provides data-binding by using the ng-model directive.

<input type="text" ng-model="firstname">

The application does now have a property named firstname.


The ng-model directive binds the input controller to the rest of your application.

The property firstname, can be referred to in a controller:

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.firstname = "John";
});
</script>

Checkbox

A checkbox has the value true or false. Apply the ng-model directive to a checkbox, and use its value in your application

Example: Show the header if the checkbox is checked:

<form>
Check to show a header:
<input type="checkbox" ng-model="myVar">
</form>
<h1 ng-show="myVar">My Header</h1>
Radiobuttons

Radio buttons with the same ng-model can have different values, but only the selected one will be used.

<body ng-app="">
<form>
Pick a topic:
<input type="radio" ng-model="myVar" value="dogs">Dogs
<input type="radio" ng-model="myVar" value="cars">Cars
</form>
<div ng-switch="myVar">
<div ng-switch-when="dogs">
<p>Welcome to a world of dogs.</p>
</div>
<div ng-switch-when="cars">
<p>Read about cars.</p>
</div>
</div>
</body>
Selectbox

The property defined in the ng-model attribute will have the value of the selected option in the selectbox.

<body ng-app="">
<form>
Select a topic:
<select ng-model="myVar">
<option value="">
<option value="dogs">Dogs
<option value="cars">Cars
</select>
</form>
<div ng-switch="myVar">
<div ng-switch-when="dogs">
<p>Welcome to a world of dogs.</p>
</div>
<div ng-switch-when="cars">
<p>Read about cars.</p>
</div>
</div>
AngularJS Form Validation

AngularJS offers client-side form validation.

AngularJS monitors the state of the form and input fields (input, textarea, select), and lets you notify the user about the
current state.

AngularJS also holds information about whether they have been touched, or modified, or not.

You can use standard HTML5 attributes to validate input, or you can make your own validation functions.

Required

Use the HTML5 attribute required to specify that the input field must be filled out:

<form name="myForm">
<input name="myInput" ng-model="myInput" required>
</form>
<h1>{{myForm.myInput.$valid}}</h1>
E-mail

Use the HTML5 type email to specify that the value must be an e-mail:

<form name="myForm">
<input name="myInput" ng-model="myInput" type="email">
</form>
<h1>{{myForm.myInput.$valid}}</h1>

Form State and Input State

AngularJS is constantly updating the state of both the form and the input fields.

Input fields have the following states:

•$untouched The field has not been touched yet


•$touched The field has been touched
•$pristine The field has not been modified yet
•$dirty The field has been modified
•$invalid The field content is not valid
•$valid The field content is valid
They are all properties of the input field, and are either true or false.

Forms have the following states:

•$pristine No fields have been modified yet


•$dirty One or more have been modified
•$invalid The form content is not valid
•$valid The form content is valid
•$submitted The form is submitted

They are all properties of the form, and are either true or false.

You can use these states to show meaningful messages to the user. Example, if a field is required, and the user leaves it blank,
you should give the user a warning:
<body ng-app="">
<p>Try leaving the first input field blank:</p>
<form name="myForm">
<p>Name:<input name="myName" ng-model="myName" required>
<span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is required.</span>
</p>
<p>Address:
<input name="myAddress" ng-model="myAddress" required>
</p>
</form>
</body>
CSS Classes

AngularJS adds CSS classes to forms and input fields depending on their states.

The following classes are added to, or removed from, input fields:

•ng-untouched The field has not been touched yet


•ng-touched The field has been touched
•ng-pristine The field has not been modified yet
•ng-dirty The field has been modified
•ng-valid The field content is valid
•ng-invalid The field content is not valid
•ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must be
validated
•ng-invalid-key Example: ng-invalid-required

The following classes are added to, or removed from, forms:

•ng-pristine No fields has not been modified yet


•ng-dirty One or more fields has been modified
•ng-valid The form content is valid
•ng-invalid The form content is not valid
•ng-valid-key One key for each validation. Example: ng-valid-required, useful when there are more than one thing that must
be validated
•ng-invalid-key Example: ng-invalid-required

The classes are removed if the value they represent is false.

Add styles for these classes to give your application a better and more intuitive user interface.

<style>
input.ng-invalid {background-color:pink;}
input.ng-valid {background-color:lightgreen;}
</style>
<body ng-app="">
<form name="myForm">
<input name="myName" ng-model="myName" required>
</form>
</body>
<style>
form.ng-pristine {background-color:lightblue;}
form.ng-dirty {background-color:pink;}
</style>
<body ng-app="">
<form name="myForm">
<input name="myName" ng-model="myName" required>
</form>
</body>

You might also like