Module-6-MVC, Angular JS (5)
Module-6-MVC, Angular JS (5)
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
• Nowadays, MVC architecture in web technology has become popular for designing
Web applications
Mobile apps
• 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
• Using these rules and guidelines, any developer can make complex applications faster and more efficiently
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
• 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:
• The ng-model directive binds the value of HTML controls (input, select, textarea) to application data.
<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 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: 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.
Creating a 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
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";
});
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.
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
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:
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.
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
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 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:
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.
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
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 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>
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.
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
<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
<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
<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 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
<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.
$scope.cars = {
car01 : "Ford",
car02 : "Fiat",
car03 : "Volvo"
};
Using an object as the data source, x represents the key, and y represents the value:
•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
<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
Data-Binding
<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
<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 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>
AngularJS is constantly updating the state of both the form and the input fields.
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:
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>