0% found this document useful (0 votes)
3 views50 pages

Module 4

AngularJS is an open-source Model-View-Controller framework primarily used for developing Single Page Applications and is maintained by Google. Key features include MVC architecture, data model binding, reduced code for DOM manipulation, and built-in testing support. The framework supports two-way data binding, routing, and custom directives, making it a powerful tool for web application development.

Uploaded by

sranjana18
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)
3 views50 pages

Module 4

AngularJS is an open-source Model-View-Controller framework primarily used for developing Single Page Applications and is maintained by Google. Key features include MVC architecture, data model binding, reduced code for DOM manipulation, and built-in testing support. The framework supports two-way data binding, routing, and custom directives, making it a powerful tool for web application development.

Uploaded by

sranjana18
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

What is AngularJS?

●​ AngularJS is an open source Model-View-Controller framework which is similar


to the JavaScript framework.
●​ AngularJS framework is used for developing mostly Single Page applications.
●​ This framework has been developed by a group of developers from Google itself.
Because of the sheer support of Google and ideas from a wide community forum,
the framework is always kept up to date. Also, it always incorporates the latest
development trends in the market.

AngularJS Features

●​ Angular has the following key features which makes it one of the powerful
frameworks in the market.
●​ MVC – The framework is built on the famous concept of MVC. This pattern is
based on splitting the business logic layer, the data layer, and presentation layer
into separate sections. The division into different sections is done so that each one
could be managed more easily.
●​ Data Model Binding – You don't need to write special code to bind data to the
HTML controls. This can be done by Angular by just adding a few snippets of
code.
●​ Writing less code – When carrying out DOM manipulation a lot of JavaScript was
required to be written to design any application. But with Angular, you will be
amazed with the lesser amount of code you need to write for DOM manipulation.
●​ Unit Testing ready – The designers at Google not only developed Angular but also
developed a testing framework called "Karma" which helps in designing unit tests
for AngularJS applications

AngularJS Architecture

•​ The Controller represents the layer that has the business logic. User events trigger
the functions which are stored inside your controller. The user events are part of
the controller.

•​ Views are used to represent the presentation layer which is provided to the end
users

•​ Models are used to represent your data. The data in your model can be as simple
as just having primitive declarations. For example, if you are maintaining a
student application, your data model could just have a student id and a name. Or it
can also be complex by having a structured data model. If you are maintaining a
car ownership application, you can have structures to define the vehicle itself in
terms of its engine capacity, seating capacity, etc.
AngularJS Advantages

●​ Since it's an open source framework, you can expect the number of errors or
issues to be minimal.
●​ Two-way binding – [Link] keeps the data and presentation layer in sync. Now
you don't need to write additional JavaScript code to keep the data in your HTML
code and your data later in sync. [Link] will automatically do this for you. You
just need to specify which control is bound to which part of your model
●​ Routing – Angular can take care of routing which means moving from one view to
another. This is the key fundamental of single page applications; wherein you can
move to different functionalities in your web application based on user interaction
but still stay on the same page.
●​ Angular supports testing, both Unit Testing, and Integration Testing.
●​ It extends HTML by providing its own elements called directives. At a high level,
directives are markers on a DOM element (such as an attribute, element name, and
comment or CSS class) that tell AngularJS's HTML compiler to attach a specified
behavior to that DOM element. These directives help in extending the
functionality of existing HTML elements to give more power to your web
application.

AngularJS MVC Architecture


MVC stands for Model View Controller. It is a software design pattern for developing web applications.
It is very popular because it isolates the application logic from the user interface layer and supports
separation of concerns.

The MVC pattern is made up of the following three parts:

1.​ Model: It is responsible for managing application data. It responds to the requests from view
and to the instructions from the controller to update itself.
2.​ View: It is responsible for displaying all data or only a portion of data to the users. It also
specifies the 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.
3.​ Controller: It is responsible to control the relation between models and views. It 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.

Modules:-
What is an AngularJS Module?

An AngularJS module is a container for different application parts and settings. It


helps in organizing code in a manageable way and is used to configure the app, define
dependencies, and bind the application logic together.

An AngularJS module defines an 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.

Creating a Module

A module is created by using the AngularJS function [Link]

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

The "myApp" parameter refers to an HTML element in which the application will
[Link] 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.
<!DOCTYPE html>
<html>
<script
src="[Link]
>
<body>

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


{{ firstName + " " + lastName }}
</div>

<script>
var app = [Link]("myApp", []);
[Link]("myCtrl", function($scope) {
$[Link] = "John";
$[Link] = "Doe";
});
</script>

</body>
</html>
Directives
AngularJS allows us to extend HTML in a very simple way using attributes. The
attributes are basically directives. There are different types of directives which can play
different roles in Application. They are App Directive, Model Directive, Bind Directive,
Init Directive, and Repeat Directive.

App Directive

ng-app= “ ”

The app directive defines the area of AngularJS application. The syntax of app directive
is ng-app = “ ”; In here the ng is the namespace of AngularJS and app is the application
area of Angular JS.
AngularJS extends HTML with ng-directives.

The ng-app directive defines an AngularJS 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.

Model Directive
Bind Directive
ng-model & ng-bind

ng-model = “data”: binds the inputted value from Html controls (textarea, checkbox,
select, input and radio etc.) to “data”.

Init Directive
Repeat Directive
Model:-
The ng-model directive binds the value of HTML controls (input, select, textarea) to
application data.

The ng-model Directive

With the ng-model directive you can bind the value of an input field to a variable created
in AngularJS.

<!DOCTYPE html>
<html>
<script
src="[Link]
>
<style>
[Link]-invalid {
background-color: lightblue;
}
</style>
<body>
<form ng-app="" name="myForm">
Enter your name:
<input name="myName" ng-model="myText" required>
</form>
<p>Edit the text field and it will get/lose classes according to the status.</p>
<p><b>Note:</b> A text field with the "required" attribute is not valid when it is
empty.</p>
</body>
</html>

AngularJS Data Binding


Data binding is a very useful and powerful feature used in software development
technologies. It acts as a bridge between the view and business logic of the application.

AngularJS follows Two-Way data binding model.

One-Way Data Binding


The one-way data binding is an approach where a value is taken from the data model and
inserted into an HTML element. There is no way to update model from view. It is used in
classical template systems. These systems bind data in only one direction.

Example:-<body ng-app="myApp" ng-controller="myController">

<h2>One-Way Data Binding Example</h2>

<p>Message: {{ message }}</p> <!-- One-way data binding -->


<input type="text" value="{{ message }}"> <!-- This does not update the model -->

<script>

var app = [Link]("myApp", []);

[Link]("myController", function($scope) {

$[Link] = "Hello, AngularJS!";

});

</script>

</body>

Two-Way Data Binding


Data-binding in Angular apps is the automatic synchronization of data between the model
and view components.

Data binding lets you treat the model as the single-source-of-truth in your application.
The view is a projection of the model at all times. If the model is changed, the view
reflects the change and vice versa.

<!DOCTYPE html>
<html>
<script src="[Link]
</script>
<body>
<div ng-app="" ng-init="firstName='Ajeet'">
<p>Input something in the input box:</p>
<p>Name: <input type="text" ng-model="firstName"></p>
<p>You wrote: {{ firstName }}</p>
</div>
</body>
</html>

In the above example, the {{ firstName }} expression is an AngularJS data binding


expression. Data binding in AngularJS binds AngularJS expressions with AngularJS data.

{{ firstName }} is bound with ng-model="firstName".

Let's take another example where two text fields are bound together with two ng-model
directives:

<!DOCTYPE html>
<html>
<script src="[Link]
</script>
<body>
<div data-ng-app="" data-ng-init="quantity=1;price=20">
<h2>Cost Calculator</h2>
Quantity: <input type="number" ng-model="quantity">
Price: <input type="number" ng-model="price">
<p><b>Total in rupees:</b> {{quantity * price}}</p>
</div>
</body>
</html>

Expressions
Filters
Controllers
Services
Angular Service Service is a function or an object, which is used to provide with a
specified action. In AngularJS, there are about 30 builtin services, such as $http,
$location, $interval and $timeout.

Types of Services in AngularJS

AngularJS provides several built-in services and also allows you to create custom
services. Here are some commonly used built-in services:

1.​ $http: For making AJAX requests.


2.​ $location: For handling URL manipulation.
3.​ $timeout: For delaying code execution.
4.​ $interval: For repeated execution at specified intervals.

Built-in AngularJS Services


1. $http (For AJAX requests)

Used to communicate with a server.

Example:
<!DOCTYPE html>
<html>
<script
src="[Link]
<body>

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

<p>Today's welcome message is:</p>

<h1>{{myWelcome}}</h1>

</div>

<p>The $http service requests a page on the server, and the response is set as the value of
the "myWelcome" variable.</p>

<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope, $http) {
$[Link]("[Link]").then(function (response) {
$[Link] = [Link];
});
});
</script>

</body>
</html>

2. $timeout (For Delayed Execution)

Executes a function after a delay.

Example:

<!DOCTYPE html>
<html>
<script
src="[Link]
<body>

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

<p>This header will change after two seconds:</p>

<h1>{{myHeader}}</h1>

</div>

<p>The $timeout service runs a function after a specified number of milliseconds.</p>

<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope, $timeout) {
$[Link] = "Hello World!";
$timeout(function () {
$[Link] = "How are you today?";
}, 2000);
});
</script>

</body>
</html>

3. $interval (For Repeated Execution)

Executes a function repeatedly at a specified time interval.

Example:
<!DOCTYPE html>
<html>
<script
src="[Link]
<body>

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

<p>The time is:</p>

<h1>{{theTime}}</h1>

</div>

<p>The $interval service runs a function every specified millisecond.</p>

<script>
var app = [Link]('myApp', []);
[Link]('myCtrl', function($scope, $interval) {
$[Link] = new Date().toLocaleTimeString();
$interval(function () {
$[Link] = new Date().toLocaleTimeString();
}, 1000);
});
</script>

</body>
</html>

4. $location

The $location service has methods which return information about the location of the
current web [Link] $location service is passed in to the controller as an argument. In
order to use the service in the controller, it must be defined as a dependency.

AngularJS constantly supervises your application, and for it to handle changes and events
properly, AngularJS prefers that you use the $location service instead of the
[Link] object.
<!DOCTYPE html>

<html>

<script
src="[Link]

<body>

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

<p>The url of this page is:</p>

<h3>{{myUrl}}</h3>

</div>

<p>This example uses the built-in $location service to get the absolute url of the
page.</p>

<script>

var app = [Link]('myApp', []);

[Link]('myCtrl', function($scope, $location) {

$[Link] = $[Link]();

});

</script>

</body>

</html>

Creating a Custom Service


Custom services can be created using:

1.​ Factory
2.​ Service
1. Using Factory

A factory function returns an object or a function that is injected where needed.

Example:

[Link]('mathService', function() {
return {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
}
};
});

//Usage in a Controller:

// Inject the Service into a Controller


[Link]('mathController', function($scope, mathService) {
$[Link] = [Link](10, 5); // 15
$[Link] = [Link](10, 5); // 5
});

Explanation:-

1.​ Factory (mathService) defines two methods:


○​ add(a, b) → Returns the sum.
○​ subtract(a, b) → Returns the difference.
2.​ Controller (mathController) calls these functions with 10 and 5, storing the results
in $[Link] and $[Link].
3.​ The results are displayed in <p>{{ addition }}</p> and <p>{{ subtraction }}</p>.

2. Using Service

In AngularJS, a service is used to share reusable code across different components like
controllers, directives, or even other services

Example:
var app = [Link]('myApp', []);

// Simple Service that returns a static message

[Link]('messageService', function() {

[Link] = function() {

return "Hello from AngularJS Service!";

};

});

// Controller using the Service

[Link]('messageController', function($scope, messageService) {

$[Link] = [Link]();

});

Explanation:-

1.​ Service (messageService) defines a function getMessage() that returns "Hello from
AngularJS Service!".
2.​ Controller (messageController) calls [Link]() and assigns the
result to $[Link].
3.​ The message "Hello from AngularJS Service!" is displayed inside <p>{{ message
}}</p>.

Dependency Injection (DI)


Dependency Injection (DI) in AngularJS is a design pattern that automatically injects
dependencies (services, factories, values, etc.) into components like controllers, services, and
directives.

<!DOCTYPE html>

<html lang="en">

<head>
<title>AngularJS Data Injection</title>

<script

src="[Link]

</head>

<body ng-app="myApp" ng-controller="MainController">

<h2>{{ message }}</h2>

<script>

var app = [Link]("myApp", []);

[Link]("DataService", function () {

[Link] = function () {

return "Hello from DataService!";

};

});

[Link]("MainController", function ($scope, DataService) {

$[Link] = [Link]();

});

</script>

</body>

</html>

Example Explained:

1.​ DataService is created as a service and injected into MainController.


2.​ AngularJS Dependency Injection (DI) automatically injects the service when
needed.
3.​ The $[Link] is updated with the return value of getMessage().
4.​ The HTML displays Hello from DataService!.

AngularJS Routing
The ngRoute module helps your application to become a Single Page Application.
What is Routing in AngularJS?

If you want to navigate to different pages in your application, but you also want the
application to be a SPA (Single Page Application), with no page reloading, you can use the
ngRoute module.

The ngRoute module routes your application to different pages without reloading the entire
application.

$routeProvider

With the $routeProvider you can define what page to display when a user clicks a link.

Now your application has access to the route module, which provides the $routeProvider.

Use the $routeProvider to configure different routes in your application

Define the $routeProvider using the config method of your application. Work registered in the
config method will be performed when the application is loading.

Template

In the previous examples we have used the templateUrl property in the $[Link]
method.

You can also use the template property, which allows you to write HTML directly in the property
value, and not refer to a page

The otherwise method

In the previous examples we have used the when method of the $routeProvider.

You can also use the otherwise method, which is the default route when none of the others get a
match.

Folder Structure

/app

|-- [Link]

|-- [Link]
|-- views/

|-- [Link]

|-- [Link]

|-- [Link]

Example:-
📄 [Link]
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>AngularJS Routing Example</title>
<script
src="[Link]
<script
src="[Link]
<script src="[Link]"></script>
</head>
<body>
<h1>AngularJS Routing Demo</h1>
<nav>
<a href="#!/">Home</a> |
<a href="#!/about">About</a> |
<a href="#!/contact">Contact</a>
</nav>
<div ng-view></div>
</body>
</html>

📄 [Link]
var app = [Link]("myApp", ["ngRoute"]);
[Link](function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "views/[Link]",
controller: "HomeCtrl"
})
.when("/about", {
templateUrl: "views/[Link]",
controller: "AboutCtrl"
})
.when("/contact", {
templateUrl: "views/[Link]",
controller: "ContactCtrl"
})
.otherwise({
redirectTo: "/"
});
});

[Link]("HomeCtrl", function($scope) {
$[Link] = "Welcome to the Home Page";
});

[Link]("AboutCtrl", function($scope) {
$[Link] = "This is the About Page";
});

[Link]("ContactCtrl", function($scope) {
$[Link] = "Get in touch through the Contact Page";
});

📄 views/[Link]
<h2>Home</h2>
<p>{{ message }}</p>

📄 views/[Link]
<h2>About</h2>
<p>{{ message }}</p>
📄 views/[Link]
<h2>Contact</h2>
<p>{{ message }}</p>

How to run

python -m [Link] 8000


[Link]
Form:-
AngularJS facilitates you to create a form enriches with data binding and validation of
input controls.

Input controls are ways for a user to enter data. A form is a collection of controls for the
purpose of grouping related controls together.

Following are the input controls used in AngularJS forms:

o​ input elements
o​ select elements
o​ button elements
o​ textarea elements
AngularJS provides multiple events that can be associated with the HTML controls.
These events are associated with the different HTML input 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:

Example
<script>​
var app=[Link]('myApp',[]);​
[Link]('formCtrl', function($scope){​
$[Link] = "John";​
});​
</script>

It can also be referred to elsewhere in the application:

Example​
<form>​
FirstName: <input type="text" ng-model="firstname">​
</form>​

<h1>You entered: {{firstname}}</h1>

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

Bind radio buttons to your application with the ng-model directive.

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

Example

Display some text, based on the value of the selected radio button:

<form>​
Pick_a_topic:​
<input type="radio" ng-model="myVar" value="dogs">Dogs​
<input type="radio" ng-model="myVar" value="tuts">Tutorials​
<input type="radio" ng-model="myVar" value="cars">Cars​
</form>

The value of myVar will be either dogs, tuts, or cars.

Selectbox

Bind select boxes to your application with the ng-model directive.

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

Example

Display some text, based on the value of the selected option:

<form>​
Select_a_topic:​
<select ng-model="myVar">​
<option value="">​
<option value="dogs">Dogs​
<option value="tuts">Tutorials​
<option value="cars">Cars​
</select>​
</form>

Example:-

<!DOCTYPE html>
<html lang="en">
<script
src="[Link]
>
<body>

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


<form novalidate>
First Name:<br>
<input type="text" ng-model="[Link]"><br>
Last Name:<br>
<input type="text" ng-model="[Link]">
<br><br>
<button ng-click="reset()">RESET</button>
</form>
<p>form = {{user}}</p>
<p>master = {{master}}</p>
</div>

<script>
var app = [Link]('myApp', []);
[Link]('formCtrl', function($scope) {
$[Link] = {firstName:"John", lastName:"Doe"};
$[Link] = function() {
$[Link] = [Link]($[Link]);
};
$[Link]();
});
</script>

</body>
</html>
Output:-

FirstName:​


LastName:​



RESET

form = {"firstName":"John","lastName":"Doe"}

master = {"firstName":"John","lastName":"Doe"}

Custom 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:

<body>

<!-- As an element -->


<w3-test-directive></w3-test-directive>

<!-- As an attribute -->


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

<!-- As a class -->


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

<script>
[Link]("myApp", [])
.directive("w3TestDirective", function() {
return {
restrict: "EAC", // allows Element, Attribute, and Class
template: "<h1>Made by a directive!</h1>"
};
});
</script>
</body>

You can invoke a directive by using:

●​ 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:

var app = [Link]("myApp", []);


[Link]("w3TestDirective", function() {
return {
restrict : "A",
template : "<h1>Made by a directive!</h1>"
};
});

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.

Components
Bing Videos

Introduction to AngularJS Components

●​ AngularJS introduced components in version 1.5.​

●​ A component is a simplified directive used to create reusable, encapsulated UI


elements.​

●​ It provides a way to define custom HTML elements and organize code modularly.​

Why Use Components?


●​ Makes code reusable and maintainable.​

●​ Follows a component-based architecture (similar to Angular 2+).​

●​ Separates logic, template, and data bindings cleanly.

Component Structure
The structure of an Angular component consists of three main parts:

1.​ Template: The template defines the HTML markup of the component's view. It

contains placeholders and Angular directives that are replaced with dynamic data
and logic during runtime.
2.​ Styles: The styles define the component's visual appearance, including CSS rules

and stylesheets. Styles can be defined using inline styles, external CSS files, or
CSS preprocessors like Sass or Less.
3.​ TypeScript Code: The TypeScript code defines the component's behavior and

logic. It includes properties, methods, and lifecycle hooks that control how the
component interacts with the DOM, handles user input, and responds to changes
in its state or props.

Syntax of AngularJS Component

[Link]('app', [])
.component('componentName', {
template: 'HTML content here',
controller: function() {
// component logic here
}
});

Basic Example

// [Link]
var app = [Link]('myApp', []);

[Link]('helloComponent', {
template: '<h2>Hello from Component!</h2>',
controller: function() {}
});

<div ng-app="myApp">
<hello-component></hello-component>
</div>

Component Configuration Options


Option Description

template HTML content as string

templateUrl Path to external HTML file

controller JavaScript function to handle logic

controllerAs Alias for controller object (default:


$ctrl)

bindings Used to bind data (like props in React)

Component with templateUrl

[Link]
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="UTF-8">
<title>Greet User Component (templateUrl)</title>
<script src="[Link]
</head>
<body>

<!-- Component usage -->


<greet-user></greet-user>
<!-- Component & Module -->
<script>
[Link]('myApp', [])
.component('greetUser', {
controller: function() {
[Link] = 'Daya';
},
templateUrl: '[Link]'
});
</script>

</body>
</html>

[Link]
<h1>Hello, {{$[Link]}}!</h1>

How to run
python -m [Link] 8000
[Link]

Component with bindings

<body>

<!-- Component usage -->


<message-box text="Welcome to AngularJS"></message-box>

<script>
// Declare module first
var app = [Link]('myApp', []);

// Register component after module declaration


[Link]('messageBox', {
bindings: {
text: '@'
},
template: '<div>Message: {{$[Link]}}</div>',
controller: function() {}
});
</script>
</body>

note:-Change @ to = to support two-way binding with a parent scope variable

Component Lifecycle
Angular components have a lifecycle consisting of various lifecycle hooks that are executed
at different stages of the component's lifecycle. These lifecycle hooks allow to hook into
specific moments in the component's lifecycle and perform actions such as initialization,
cleanup, or handling changes.
Some of the most commonly used lifecycle hooks include:
●​ ngOnInit: Called after the component's inputs are initialized and the component's
view has been initialized.
●​ ngOnChanges: Called whenever the component's inputs change.
●​ ngOnDestroy: Called when the component is being destroyed and cleaned up.

[Link]

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script
src="[Link]
/script>
<script src="component_lifecycle_app.js"></script>
</head>
<body ng-controller="MainCtrl as main">
<button ng-click="[Link]()">
Toggle Component
</button>
<button ng-click="[Link]()">
Change Name
</button>
<lifecycle-demo ng-if="[Link]"
name="{{[Link]}}"></lifecycle-demo>
</body>
</html>

[Link]

[Link]('myApp', [])
.controller('MainCtrl', function () {
[Link] = 'Alice';
[Link] = true;
[Link] = () => {
[Link] = [Link] === 'Alice' ? 'Bob' : 'Alice';
};
[Link] = () => {
[Link] = ![Link];
};
})
.component('lifecycleDemo', {
bindings: {
name: '@'
},
controller: function ($log) {
this.$onInit = () => {
$[Link]('$onInit: Initialized with name =', [Link]);
};

this.$onChanges = (changes) => {


$[Link]('$onChanges:', changes);
};

this.$onDestroy = () => {
$[Link]('$onDestroy: Component is being destroyed');
};
},
template: `<div><p>Hello, {{$[Link]}}</p></div>`
});

Difference Between Component and Directive


Component Directive

Used to create UI components Used to add custom behavior

Simplified configuration Requires manual setup

Follows component-based design May mix logic and view

Introduced in AngularJS 1.5 Present since AngularJS 1.0

Advantages of Components

●​ Encourages modular development​

●​ Improves code reusability​

●​ Supports hierarchical nesting​


●​ Easier to test and maintain​

●​ Seamless migration path to Angular 2+

You might also like