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

How to write a Program using Angular JS.docx

The document provides a comprehensive guide on how to write a program using AngularJS, covering key concepts such as directives, expressions, and controllers. It includes examples of using built-in directives like ng-model, ng-bind, and ng-repeat, as well as custom directives and filters. Additionally, it explains form validation and the use of modules in AngularJS applications.

Uploaded by

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

How to write a Program using Angular JS.docx

The document provides a comprehensive guide on how to write a program using AngularJS, covering key concepts such as directives, expressions, and controllers. It includes examples of using built-in directives like ng-model, ng-bind, and ng-repeat, as well as custom directives and filters. Additionally, it explains form validation and the use of modules in AngularJS applications.

Uploaded by

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

How to write a Program using Angular JS?

AngularJS is a JavaScript framework. It can be added to an


HTML page with a <script> tag. AngularJS extends HTML
attributes with Directives, and binds data to HTML with
Expressions.
<!doctype html>
<html ng-app>

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

AngularJS Expressions

Expressions in AngularJS are used to bind application data to


HTML. The expressions are resolved by AngularJS and the result
is returned back to where the expression is written. The
expressions in AngularJS are written in double braces:
{{ expression }}.
They behave similar to ng-bind directives: ng-bind=”expression”.
1> Refer Addition in Javascript
<!DOCTYPE html>
<html ng-app>

<head>

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

<div>

{{['vs', 'ds', 'es'][2]}}

</div>

<div>
4 + 8 = {{4 + 8}}
</div>
</body>
</html>

2-a>Refer prompt of javascript,ng-model

The ngModel directive is a directive that is used to bind the values of the HTML
controls (input, select, and textarea) or any custom form controls, and stores the
required user value in a variable and we can use that variable whenever we require
that value.

<!doctype html>
<html ng-app>

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

<body>
<div>
<label>Name:</label>
<input type = "text" ng-model = "yourName" placeholder = "Enter a name here">

<h1>Hello {{yourName}}!</h1>
</div>
</body>
</html>

2- b>ng-model, ng-init

The ng-init Directive is used to initialize AngularJS Application data. It defines


the initial value for an AngularJS application and assigns values to the variables.
The ng-init directive defines initial values and variables for an AngularJS
application. Syntax: <ng element -init = "expression">

<!DOCTYPE html>
<html ng-app>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-init = "quantity=1; price=5">

<h2>Cost Calculator</h2>

Quantity: <input type="number" ng-model="quantity">


Price: <input type="number" ng-model="price">

<p><b>Total in dollar:</b> {{quantity * price}}</p>

</div>

</body>
</html>

Steps to write a program

Step 1 − Load framework


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

Step 2 - Define AngularJS Application using ng-app directive


<body ng-app="myapp">

Step 3 - Define a model name using ng-model directive


<input type = "text" ng-model = "yourName" placeholder = "Enter a name here">

Step 4 - Bind the value of the above model defined using ng-bind directive.
<p>Hello <span ng-bind="name"></span>!</p>

3>Program with ng-bind

The ng-bind directive tells AngularJS to replace the content of an HTML


element with the value of a given variable, or expression. If the value of the
given variable, or expression, changes, the content of the specified HTML
element will be changed as well.

<!doctype html>
<html ng-app>

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

<body>
<div>
<label>Name:</label>
<input type = "text" ng-model = "yourName" placeholder = "Enter a name here">

<hr />

<h1>Hello <span ng-bind = "yourName">!</span></h1>

</div>
</body>
</html>
{{yourName}}

built-inAngularJS directives.

Directive Description
ng-app Auto bootstrap AngularJS application.
ng-init Initializes AngularJS variables
ng-model Binds HTML control's value to a property on the $scope object.
ng-control
Attaches the controller of MVC to the view.
ler
Replaces the value of HTML control with the value of specified
ng-bind
AngularJS expression.
Repeats HTML template once per each item in the specified
ng-repeat
collection.
Display HTML element based on the value of the specified
ng-show
expression.
ng-readon Makes HTML element read-only based on the value of the
ly specified expression.
ng-disable Sets the disable attribute on the HTML element if specified
d expression evaluates to true.
ng-if Removes or recreates HTML element based on an expression.
ng-click Specifies custom behavior when an element is clicked.

4-a>ng-repeat
<!DOCTYPE html>
<htmlng-app>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<div ng-init = "names=['Tom','Jerry','Donald']">
<p>ng-repeat directive:</p>
<ol>
<li ng-repeat="x in names">
{{ x }}
</li>
</ol>
</div>

</body>
</html>

4-b>ng–repeat
<!doctype html>
<html ng-app>

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

<body>
<div ng-init = "names = [{name:'Tom',age:'25'},
{name:'Jerry',age:'30'}, {name:'Donald',age:'28'}]">

<p>List of Name and Age:</p>

<ol>
<li ng-repeat = "x in names">
{{ 'Students Name: ' + x.name + ', Students Age: ' +
x.age }}
</li>
</ol>

</div>

</body>
</html>

Exercise: take input of first and last name, marks of 2 subjects. And display the avg.

5>ng-enabled ,disabled directives


<!DOCTYPE html>
<html>

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

<body>
<h2>AngularJS Enable/disabled Application</h2>
<div ng-app = "">

<input type = "checkbox" ng-model = "enableDisableButton">Disable Button</br>


<button ng-disabled = "enableDisableButton">Click Me!</button></br>

<input type = "checkbox" ng-model = "showHide1">Show Button


<button ng-show = "showHide1">Click Me!</button></br>

<input type = "checkbox" ng-model = "showHide2">Hide Button


<button ng-hide = "showHide2">Click Me!</button></br>
<button ng-click = "clickCounter = clickCounter + 1">Click Me!</button>
<p>Total click: {{ clickCounter }}</p>

</div>

</body>
</html>

AngularJS Custom Directives


Custom directives are used in AngularJS to extend the functionality of HTML. Custom

directives are defined using the "directive" function. A custom directive simply replaces

the element for which it is activated.

AngularJS provides support to create custom directives for the following type of

elements.

● Element directives − Directive activates when a matching element is

encountered.

● Attribute − Directive activates when a matching attribute is encountered.

● CSS − Directive activates when a matching css style is encountered.

● Comment − Directive activates when a matching comment is encountered.

6a>ng-controller
The ng-controller directive adds a controller to your application. In the
controller you can write code, and make functions and variables, which will be
parts of an object, available inside the current HTML element. In AngularJS this
object is called a scope.
<!DOCTYPE html>
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>

<body ng-app="myNgApp">
<h2>AngularJS Controller</h2>

<div ng-controller="myController">
{{message}}
</div>
<script>
var ngApp = angular.module('myNgApp', []);

ngApp.controller('myController', function ($scope) {


$scope.message = "Hello World!";
});
</script>
</body>
</html>

</body>
</html>
6 –b>
<!DOCTYPE html>
<html>

<head>
<title>Angular JS Controller</title>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>

<body>
<h2>AngularJS Sample Application</h2>

<div ng-app = "mainApp" ng-controller = "studentController">


Enter first name: <input type = "text" ng-model = "student.firstName"><br><br>
Enter last name: <input type = "text" ng-model = "student.lastName"><br>
<br>

You are entering: {{student.fullName()}}


</div>

<script>
varmainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Tom",
lastName: "Jerry",

fullName: function() {
varstudentObject;
studentObject = $scope.student;
returnstudentObject.firstName + " " + studentObject.lastName;
}
};
});
</script>

</body>
</html>

7) module

ngModule in Angular refers to a place where you can group the components,
directives, pipes, and services, which are related to the application.The module
is a container for the different parts of an application. The module is a
container for the application controllers. Controllers always belong to a
module.

<!DOCTYPE html>
<html ng-app = "myModule">

<head>

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


</head>
<body>
<div ng-controller = "myController">
{{message}}
</div>
<div>
4 + 8 = {{4 + 8}}
</div>
<script>
var myApp = angular.module("myModule",[]);
myApp.controller('myController', function ($scope){
$scope.message = "AngularJS";
});
</script>

8) AngularJS Filter -
● AngularJS Filters allow us to format the data to display on UI without changing the
original format.
● Filters can be used with an expression or directives using pipe | sign.
{{expression | filterName:parameter }}
● Angular includes various filters to format data of different data types.

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 lowercase.
● number Format a number to a string.
● orderBy Orders an array by an expression.
● uppercase Format a string to uppercase.

Currency -
<!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="costCtrl">

<h1>Price: {{ price | currency }}</h1>


</div>

<script>
var app = angular.module('myApp', []);
app.controller('costCtrl', function($scope) {
$scope.price = 60;
});
</script>

</body>
</html>
2 Date
<div ng-app="myApp" ng-controller="datCtrl">

<p>Date = {{ today | date }}</p>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('datCtrl', function($scope) {
$scope.today = new Date();
});
</script>
3 Filter
<div ng-app="myApp" ng-controller="namesCtrl">

<ul>
<li ng-repeat="x in names | filter : 'i'">
{{ x }}
</li>
</ul>

</div>

<script>
var myApp = angular.module('myApp', []);
myApp.controller('namesCtrl', function($scope) {
$scope.names = [
'Jani',
'Carl',
'Margareth',
'Hege',
'Joe',
'Gustav',
'Birgit',
'Mary',
'Kai'
];
});
</script>

4 JSON
<div ng-app="myApp" ng-controller="jsCtrl">

{{customer | json}}

</div>

<script>
var app = angular.module('myApp', []);
app.controller('jsCtrl', function($scope) {
$scope.customer = {
"name" : "Alfreds Futterkiste",
"city" : "Berlin",
"country" : "Germany"
};
});

</script>

UpperCase LowerCase -
<div ng-app="myApp" ng-controller="personCtrl">

<p>The name is {{ lastName | uppercase }}</p>


<p>The name is {{ firstName | lowercase }}</p>

</div>

<script>
angular.module('myApp', []).controller('personCtrl', function($scope) {
$scope.firstName = "John",
$scope.lastName = "Doe"
});
</script>

Orderby

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

<ul>
<li ng-repeat="x in cars | orderBy">{{x}}</li>
</ul>

</div>

<script>
var app = angular.module('myApp', []);
app.controller('orderCtrl', function($scope) {
$scope.cars = ["Dodge", "Fiat", "Audi", "Volvo", "BMW", "Ford"];
});
</script>

8>Form

Validate Form data

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
Directive Description

ng-required Sets required attribute on an input field.

ng-minlength Sets minlength attribute on an input field.

ng-maxlength Sets maxlength attribute on an input field. Setting the


attribute to a negative or non-numeric value, allows
view values of any length.

ng-pattern Sets pattern validation error key if the ngModel value


does not match the specified Reg expression.

<!DOCTYPE html>
<html>
<head>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h2>AngularJS Form</h2>
<div ng-app = "mainApp" ng-controller = "studentController">

<form name = "studentForm" novalidate>


<div>
Enter first name:
<input name = "firstname" type = "text" ng-model = "firstName" required>
<span style = "color:red" ng-show = "studentForm.firstname.$dirty &&
studentForm.firstname.$invalid">
<span ng-show = "studentForm.firstname.$error.required">First Name is
required.</span>
</div>

<div>
Enter last name:
<input name = "lastname" type = "text" ng-model = "lastName" required>
<span style = "color:red" ng-show = "studentForm.lastname.$dirty &&
studentForm.lastname.$invalid">
<span ng-show = "studentForm.lastname.$error.required">Last Name is required.</span>
</span>

</div>

<div>
Email: </td><td><input name = "email" type = "email" ng-model = "email"
length = "100" required>
<span style = "color:red" ng-show =
"studentForm.email.$dirty&&studentForm.email.$invalid">
<span ng-show = "studentForm.email.$error.required">Email is required.</span>
<span ng-show = "studentForm.email.$error.email">Invalid email address.</span>
</span>

</div>
<button ng-click = "reset()">Reset</button>

<button ng-disabled = "studentForm.firstname.$dirty &&


studentForm.firstname.$invalid || studentForm.lastname.$dirty &&
studentForm.lastname.$invalid || studentForm.email.$dirty&&
studentForm.email.$invalid" ng-click="submit()">Submit</button>

</form>
</div>

<script>
var mainApp = angular.module("mainApp", []);

mainApp.controller('studentController', function($scope) {
$scope.reset = function(){
$scope.firstName = "";
$scope.lastName = "";
$scope.email = "";
}

$scope.reset();
});
</script>

</body>
</html>
9>AJAX
Data.txt
[
{
"Name" : "Vikas",
"RollNo" : 101,
"Percentage" : "80%"
},

{
"Name" : "Pranav",
"RollNo" : 102,
"Percentage" : "70%"
},

{
"Name" : "Rohit",
"RollNo" : 103,
"Percentage" : "75%"
},

{
"Name" : "Atharv",
"RollNo" : 110,
"Percentage" : "77%"
}
]
Test.html
<html>
<head>
<title>Angular JS Ajax</title>

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


</head>
<body>
<h2>AngularJS with Database</h2>
<div ng-app = "" ng-controller = "studentController">

<table border="1">
<tr>
<th>Name</th>
<th>Roll No</th>
<th>Percentage</th>
</tr>

<trng-repeat = "student in students">


<td>{{ student.Name }}</td>
<td>{{ student.RollNo }}</td>
<td>{{ student.Percentage }}</td>
</tr>
</table>
</div>

<script>
functionstudentController($scope,$http) {
varurl = "data.txt";

$http.get(url).then( function(response) {
$scope.students = response.data;
});
}
</script>

</body>
</html>

10] AngularJS Routing


ng-View, ng-template, $routeProvider
AngularJS supports Single Page Application via multiple views on a single page. To do this
AngularJS has provided ng-view and ng-template directives and $routeProvider services.
ng-view
ng-view tag simply creates a placeholder where a corresponding view (html or ng-template view)
can be placed

ng-template
ng-template directive is used to create an html view using script tag. It contains an "id" attribute
which is used by $routeProvider to map a view with a controller.

$routeProvider
$routeProvider is the key service which set the configuration of urls, map them with the
corresponding html page or ng-template, and attaches a controller with the same.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>

<body ng-app="myApp">

<p><a href="#/!">Main</a></p>

<a href="#!banana">Banana</a>
<a href="#!tomato">Tomato</a>

<p>Click on the links to change the content.</p>

<p>The HTML shown in the ng-view directive are written in the template property of the
$routeProvider.when method.</p>

<div ng-view></div>

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
template : "<h1>Main</h1><p>Click on the links to change this content</p>"
})
.when("/banana", {
template : "<h1>Banana</h1><p>Bananas contain around 75% water.</p>"
})
.when("/tomato", {
template : "<h1>Tomato</h1><p>Tomatoes contain around 95% water.</p>"
});
});
</script>

</body>
</html>

*********

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

<body ng-app="myApp">

<p><a href="#/!">Main</a></p>

<a href="#!HTML">Course-1</a>
<a href="#!Javascript">Course-2</a>

<p>Click on the links to read about the various courses.</p>

<div ng-view></div>

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.html"
})
.when("/HTML", {
templateUrl : "HTML.html"
})
.when("/Javascript", {
templateUrl : "Javascript.html"
});
});
</script>
</body>
</html>
*****************
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular-route.js"></script>

<body ng-app="myApp">

<p><a href="#/!">Main</a></p>

<a href="#!london">City 1</a>


<a href="#!paris">City 2</a>

<p>Click on the links to read about London and Paris.</p>

<div ng-view></div>

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "main.htm"
})
.when("/london", {
templateUrl : "london.htm"
})
.when("/paris", {
templateUrl : "paris.htm"
});
});
</script>

</body>
</html>

11] Dependency Injection


Dependency Injection is a software design pattern in which components are given their
dependencies instead of hard coding them within the component. This relieves a component
from locating the dependency and makes dependencies configurable. This helps in making
components reusable, maintainable and testable.
https://www.tutorialspoint.com/angularjs/angularjs_dependency_injection.htm

<!DOCTYPE html>
<html>
<head>
<title>AngularJS Dependency Injection</title>
</head>

<body>
<h2>AngularJS Sample Application</h2>

<div ng-app = "mainApp" ng-controller = "CalcController">


<p>Enter a number: <input type = "number" ng-model = "number" /></p>
<button ng-click = "square()">X<sup>2</sup></button>
<p>Result: {{result}}</p>
</div>

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

<script>
var mainApp = angular.module("mainApp", []);

mainApp.config(function($provide) {
$provide.provider('MathService', function() {
this.$get = function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b;
}
return factory;
};
});
});

mainApp.value("defaultInput", 5);

mainApp.factory('MathService', function() {
var factory = {};

factory.multiply = function(a, b) {
return a * b;
}
return factory;
});
mainApp.service('CalcService', function(MathService) {
this.square = function(a) {
return MathService.multiply(a,a);
}
});
mainApp.controller('CalcController', function($scope, CalcService,
defaultInput) {
$scope.number = defaultInput;
$scope.result = CalcService.square($scope.number);

$scope.square = function() {
$scope.result = CalcService.square($scope.number);
}
});
</script>

</body>
</html>

12] Custom Directives


<head>
<title>Angular JS Custom Directives</title>
</head>

<body>
<h2>AngularJS Sample Application</h2>

<div ng-app = "mainApp" ng-controller = "StudentController">


<student name = "Mahesh"></student><br/>
<student name = "Piyush"></student>
</div>

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

<script>
varmainApp = angular.module("mainApp", []);

mainApp.directive('student', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Student: <b>{{student.name}}</b> , Roll No: <b>{{student.rollno}}</b>";

directive.scope = {
student : "=name"
}

directive.compile = function(element, attributes) {


element.css("border", "1px solid #cccccc");
varlinkFunction = function($scope, element, attributes) {
element.html("Student: <b>"+$scope.student.name +"</b> , Roll No:
<b>"+$scope.student.rollno+"</b><br/>");
element.css("background-color", "#ff00ff");
}
returnlinkFunction;
}

return directive;
});

mainApp.controller('StudentController', function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.name = "Mahesh Parashar";
$scope.Mahesh.rollno = 1;

$scope.Piyush = {};
$scope.Piyush.name = "PiyushParashar";
$scope.Piyush.rollno = 2;
});

</script>

</body>
</html>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy