0% found this document useful (0 votes)
23 views94 pages

Angular JS QPS Solutions

The document provides an overview of AngularJS, highlighting its advantages such as two-way data binding and modular architecture. It explains key concepts like controllers, directives (ng-app, ng-model, ng-show, ng-if), and services, along with examples of their usage. Additionally, it covers the differences between $scope and $rootScope, the MVC architecture, and various methods of the $scope object.

Uploaded by

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

Angular JS QPS Solutions

The document provides an overview of AngularJS, highlighting its advantages such as two-way data binding and modular architecture. It explains key concepts like controllers, directives (ng-app, ng-model, ng-show, ng-if), and services, along with examples of their usage. Additionally, it covers the differences between $scope and $rootScope, the MVC architecture, and various methods of the $scope object.

Uploaded by

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

ANGULAR-JS QPS SOLUTIONS

QP1

Sure! Here's a concise overview of each topic:

a) **Two Advantages of AngularJS:**

1. **Two-Way Data Binding:** AngularJS synchronizes data between the model and view
automatically. This means that when the data in the model changes, the view reflects those changes
and vice versa, reducing the need for manual DOM manipulation.

2. **Modular Architecture:** AngularJS promotes a modular architecture, which allows developers


to create reusable components and services. This enhances code organization and maintainability.

b) **Two Editors Used for AngularJS:**

1. **Visual Studio Code (VS Code):** A popular, lightweight code editor with support for AngularJS
through various extensions.

2. **Sublime Text:** A versatile text editor known for its speed and support for AngularJS
development through plugins.

c) **Two-Way Data Binding:**

Two-way data binding in AngularJS allows automatic synchronization of data between the model
and the view. When data in the model changes, the view updates automatically, and any changes in
the view are reflected back to the model. This reduces the need for explicit DOM manipulation and
ensures consistency between the user interface and the underlying data.

d) **What is Controller?**

In AngularJS, a controller is a JavaScript function that is used to build and manage the data model
for a view. It is responsible for initializing data, handling user inputs, and updating the view. However,
in your preferred approach, you focus on using directives and avoid controllers.

e) **Explain ng-app Directive:**

The `ng-app` directive initializes an AngularJS application. It defines the root element of the
application and triggers AngularJS’s compilation process for the contained HTML elements. It is
typically placed in the HTML tag or a parent element that encloses the entire AngularJS application.

f) **What is Dependency Injection?**


Dependency Injection (DI) is a design pattern used in AngularJS to manage dependencies in an
application. It allows you to inject services, functions, or objects into components, rather than
hardcoding them, facilitating better modularity and testability. DI helps in creating reusable and
maintainable code by decoupling components from their dependencies.

g) **Use of ng-show:**

The `ng-show` directive is used to conditionally display elements based on a boolean expression. If
the expression evaluates to `true`, the element is shown; otherwise, it is hidden. It controls the
visibility of elements without removing them from the DOM.

h) **Short Note on $scope:**

The `$scope` object in AngularJS is used to bind data between the controller and the view. It acts as
an intermediary that allows data to be shared and manipulated within the application. However, in
your approach focusing on directives, `$scope` is not used.

i) **Explain ng-if Directive:**

The `ng-if` directive conditionally includes or excludes an HTML element from the DOM based on
the evaluation of an expression. If the expression evaluates to `true`, the element is added to the
DOM; otherwise, it is removed. This is useful for dynamically managing the presence of elements in
the view.

j) **What are Form Events?**

Form events refer to the various actions or occurrences associated with form elements, such as
input fields, buttons, and selects. Examples include `ng-submit` (triggered when a form is submitted),
`ng-change` (triggered when the value of an input field changes), and `ng-focus`/`ng-blur` (triggered
when an element gains or loses focus). These events are used to handle user interactions and control
form behavior in AngularJS applications.

Here are detailed answers to your questions:

a) **Explain ng-model in Detail with Example:**

The `ng-model` directive in AngularJS binds the value of HTML controls (like input fields, select
boxes, and text areas) to a variable in the AngularJS application’s scope. This creates a two-way data
binding between the view and the model, meaning changes to the input field update the variable
and changes to the variable update the input field.
**Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>ng-model Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.name = 'John Doe';

});

</script>

</head>

<body ng-controller="myCtrl">

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

<p>Hello, {{name}}!</p>

</body>

</html>

```

**Explanation:**

- `ng-model="name"` binds the input field to the `name` variable in the `$scope`.

- When you type into the input field, the `name` variable updates in real-time.

- The `<p>` element displays the current value of `name`, reflecting changes instantly due to the
two-way data binding.

b) **Three Directives Used in AngularJS:**

1. **ng-repeat:** Used to iterate over a collection and render a template for each item.
```html

<div ng-repeat="item in items">{{item}}</div>

```

2. **ng-bind:** Binds the content of an HTML element to a variable in the scope.

```html

<span ng-bind="message"></span>

```

3. **ng-show:** Conditionally shows or hides an element based on an expression.

```html

<div ng-show="isVisible">This is visible when isVisible is true.</div>

```

c) **Advantages of Creating Modules:**

1. **Organizational Structure:** Modules help in organizing code into reusable components and
services, making it easier to manage and scale large applications.

2. **Dependency Management:** Modules provide a way to manage dependencies between


different parts of the application. Services and components can be injected into other components,
promoting modularity and reducing tight coupling.

3. **Improved Maintainability:** By splitting the application into smaller modules, it becomes


easier to maintain and test individual parts of the application, leading to better code quality.

d) **AngularJS Program to Enter Two Numbers and Display Multiplication Result:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Multiply Numbers</title>

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

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.num1 = 0;

$scope.num2 = 0;

$scope.result = 0;

$scope.multiply = function() {

$scope.result = $scope.num1 * $scope.num2;

};

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Number 1: <input type="number" ng-model="num1"></p>

<p>Number 2: <input type="number" ng-model="num2"></p>

<button ng-click="multiply()">Multiply</button>

<p>Result: {{result}}</p>

</body>

</html>

```

**Explanation:**

- `ng-model="num1"` and `ng-model="num2"` bind the input fields to `num1` and `num2` in the
`$scope`.

- The `ng-click="multiply()"` directive calls the `multiply` function when the button is clicked.

- The `multiply` function calculates the product of `num1` and `num2` and updates the `result`.

e) **AngularJS Program to Showcase the Use of ng-click:**

```html

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

<head>

<title>ng-click Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.message = 'Hello, World!';

$scope.changeMessage = function() {

$scope.message = 'You clicked the button!';

};

});

</script>

</head>

<body ng-controller="myCtrl">

<p>{{message}}</p>

<button ng-click="changeMessage()">Click Me!</button>

</body>

</html>

```

**Explanation:**

- The `ng-click="changeMessage()"` directive binds the button click event to the `changeMessage`
function.

- When the button is clicked, the `changeMessage` function updates the `message` variable.

- The paragraph displays the current value of `message`, which changes when the button is clicked.

Here's a detailed explanation of each question:

a) **Difference Between $rootScope and $scope:**


- **$scope:**

- **Scope:** `$scope` is a built-in AngularJS object that represents the application model. It is
used within a specific controller or directive to bind data between the controller and the view.

- **Hierarchy:** `$scope` is hierarchical, meaning that it is inherited from parent scopes. Each
controller or directive gets its own `$scope` object.

- **Usage:** It is used to manage data specific to a view or controller.

- **$rootScope:**

- **Scope:** `$rootScope` is a parent object of all `$scope` objects created in an AngularJS


application. It serves as a global scope and is accessible from any controller or directive in the
application.

- **Hierarchy:** It does not have a parent, making it a global scope accessible from anywhere
within the application.

- **Usage:** It is used to store data or functions that need to be accessible throughout the
application, but overuse can lead to tight coupling and potential issues with maintainability.

**Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>$scope vs $rootScope</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('parentCtrl', function($scope, $rootScope) {

$scope.parentMessage = "Message from parent scope";

$rootScope.globalMessage = "Message from root scope";

});

app.controller('childCtrl', function($scope, $rootScope) {

$scope.childMessage = "Message from child scope";

});
</script>

</head>

<body ng-controller="parentCtrl">

<p>{{parentMessage}}</p>

<p>{{globalMessage}}</p>

<div ng-controller="childCtrl">

<p>{{childMessage}}</p>

<p>{{globalMessage}}</p>

</div>

</body>

</html>

```

**Explanation:**

- `parentMessage` is specific to the `parentCtrl` scope.

- `globalMessage` is defined on `$rootScope` and accessible from any controller.

- `childMessage` is specific to `childCtrl`, while `globalMessage` is inherited from `$rootScope`.

b) **Purposes of AngularJS Services:**

- **Purpose:** AngularJS services are singleton objects or functions that are used to organize and
share code across different parts of an application. They typically handle data management, business
logic, and communication with servers.

- **Purpose of Services:**

- Encapsulate and manage application logic and data.

- Share data and functions across controllers and components.

- Simplify the application structure by promoting reusable and modular code.

**Two Common Services:**

1. **$http:** Used to make AJAX requests to a server.

2. **$location:** Provides methods to interact with the browser’s URL, including navigating and
manipulating the URL.
c) **MVC Architecture in Detail:**

**MVC (Model-View-Controller) Architecture:**

- **Model:**

- **Role:** Represents the data and business logic of the application. It interacts with the
database and performs operations on the data.

- **Example:** In AngularJS, services or factory functions often serve as the model, handling data
operations and business logic.

- **View:**

- **Role:** Represents the user interface of the application. It displays data to the user and
provides a way for users to

**MVC Architecture in Detail (continued):**

- **View:**

- **Role:** Represents the user interface of the application. It displays data to the user and
provides a way for users to interact with the application.

- **Example:** In AngularJS, HTML templates with Angular directives (`ng-bind`, `ng-repeat`, etc.)
are used to create the view.

- **Controller:**

- **Role:** Acts as an intermediary between the Model and the View. It processes user inputs,
updates the Model, and refreshes the View.

- **Example:** In AngularJS, controllers (or directives in your case) manage the data and handle
user interactions, updating the view accordingly.

**How It Works:**

- The user interacts with the View.

- The Controller receives user input from the View and updates the Model.

- The Model performs business logic and data manipulation.


- The View is updated based on changes in the Model.

**Diagram Example:**

```

[View] <-- user input --> [Controller] <-- data manipulation --> [Model]

[Model] <-- data updates --> [View]

```

d) **Program to Demonstrate the Use of ng-controller:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>ng-controller Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.greeting = 'Hello, World!';

});

</script>

</head>

<body>

<div ng-controller="myCtrl">

<p>{{greeting}}</p>

</div>

</body>

</html>

```
**Explanation:**

- The `ng-controller="myCtrl"` directive specifies that the `myCtrl` controller will manage the scope
for the `div`.

- The `myCtrl` controller initializes the `$scope.greeting` variable, which is then bound to the view
and displayed.

e) **Simple Program to Show the Use of $scope:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>$scope Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.message = 'Welcome to AngularJS!';

});

</script>

</head>

<body ng-controller="myCtrl">

<p>{{message}}</p>

</body>

</html>

```

**Explanation:**

- The `ng-controller="myCtrl"` directive attaches the `myCtrl` controller to the `body` element.

- The `myCtrl` controller defines `$scope.message`, which is bound to the `<p>` element and
displayed.
4

Here are detailed answers to each question:

a) **Four Methods of $scope Object:**

1. **$watch(expression, listener, [objectEquality]):**

- **Purpose:** Watches an expression for changes and executes a listener function when the
expression changes.

- **Parameters:**

- `expression`: The expression to watch.

- `listener`: A function to execute when the expression changes.

- `objectEquality` (optional): A boolean that determines whether to check for deep object
equality.

- **Example:**

```javascript

$scope.$watch('myVar', function(newValue, oldValue) {

console.log('Value changed from', oldValue, 'to', newValue);

});

```

2. **$apply([expr]):**

- **Purpose:** Executes an expression and triggers a digest cycle, updating the view.

- **Parameters:**

- `expr` (optional): The expression to execute. If not provided, `$apply` will use the current
scope.

- **Example:**

```javascript

$scope.$apply(function() {

$scope.myVar = 'New Value';

});

```
3. **$emit(eventName, [args]):**

- **Purpose:** Dispatches an event upwards through the scope hierarchy.

- **Parameters:**

- `eventName`: The name of the event to dispatch.

- `args` (optional): Arguments to pass with the event.

- **Example:**

```javascript

$scope.$emit('myEvent', {data: 'someData'});

```

4. **$broadcast(eventName, [args]):**

- **Purpose:** Dispatches an event downwards through the scope hierarchy.

- **Parameters:**

- `eventName`: The name of the event to dispatch.

- `args` (optional): Arguments to pass with the event.

- **Example:**

```javascript

$scope.$broadcast('myEvent', {data: 'someData'});

```

b) **Working of Uppercase and Lowercase Filters:**

- **Uppercase Filter:** Transforms a string to uppercase.

- **Lowercase Filter:** Transforms a string to lowercase.

**Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>
<title>Filters Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.text = 'Hello World!';

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Original: {{text}}</p>

<p>Uppercase: {{text | uppercase}}</p>

<p>Lowercase: {{text | lowercase}}</p>

</body>

</html>

```

**Explanation:**

- `{{text | uppercase}}` transforms the string `text` to uppercase.

- `{{text | lowercase}}` transforms the string `text` to lowercase.

c) **AngularJS Services:**

- **$document Service:**

- **Purpose:** Provides access to the document object, allowing interaction with the DOM.

- **Usage:** You can use `$document` to access and manipulate the DOM in a way similar to
using `document` in vanilla JavaScript.

- **Example:**

```javascript

app.controller('myCtrl', function($scope, $document) {

$document[0].body.style.backgroundColor = 'lightblue';
});

```

- **$log Service:**

- **Purpose:** Provides a logging service for debugging purposes. It supports different log levels
like `log`, `warn`, `error`, and `info`.

- **Usage:** Use `$log` to print messages to the browser console.

- **Example:**

```javascript

app.controller('myCtrl', function($scope, $log) {

$log.info('This is an info message');

$log.warn('This is a warning message');

$log.error('This is an error message');

});

```

- **$rootScope Service:**

- **Purpose:** Provides a global scope accessible from any controller or directive. It can be used
to share data or functions globally across the application.

- **Usage:** Use `$rootScope` to store properties or methods that need to be accessed


throughout the application.

- **Example:**

```javascript

app.run(function($rootScope) {

$rootScope.globalData = 'Global Information';

});

```

d) **AngularJS Program to Create a Service to Find Whether the Entered Number is Prime or Not:**

```html

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

<head>

<title>Prime Number Service</title>

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

<script>

var app = angular.module('myApp', []);

app.service('primeService', function() {

this.isPrime = function(num) {

if (num <= 1) return false;

for (var i = 2; i < num; i++) {

if (num % i === 0) return false;

return true;

};

});

app.controller('myCtrl', function($scope, primeService) {

$scope.number = null;

$scope.checkPrime = function() {

$scope.result = primeService.isPrime($scope.number) ? 'Prime' : 'Not Prime';

};

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Enter a number: <input type="number" ng-model="number"></p>

<button ng-click="checkPrime()">Check Prime</button>

<p>Result: {{result}}</p>

</body>

</html>
```

**Explanation:**

- The `primeService` service contains a method `isPrime` to determine if a number is prime.

- The `myCtrl` controller uses this service to check if the entered number is prime and displays the
result.

e) **Program to Generate Numbers After an Interval of Every 1000 ms:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Number Generator</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope, $interval) {

var count = 0;

$scope.numbers = [];

$interval(function() {

$scope.numbers.push(count++);

}, 1000);

});

</script>

</head>

<body ng-controller="myCtrl">

<ul>

<li ng-repeat="number in numbers">{{number}}</li>


</ul>

</body>

</html>

```

**Explanation:**

- The `$interval` service is used to execute a function every 1000 milliseconds (1 second).

- The function increments a counter and adds it to the `numbers` array.

- The view updates automatically to display the numbers generated every second.

Here are concise explanations for each topic:

a) **Single Page Application (SPA):**

- **Definition:** A Single Page Application (SPA) is a type of web application that interacts with the
user by dynamically rewriting the current page, rather than loading entire new pages from the server.
This approach improves user experience by creating a more fluid and responsive interface.

- **Characteristics:**

- **Dynamic Loading:** Content is loaded dynamically as needed without refreshing the entire
page.

- **Client-Side Routing:** Uses client-side routing to navigate between different views or states
without reloading the page.

- **Improved Performance:** Reduces server load and decreases latency by minimizing the
amount of data transferred between the client and server.

**Example:**

AngularJS is commonly used to build SPAs, where directives and routing manage dynamic content
updates within a single HTML page.

b) **Explain ng-model and ng-required:**

- **ng-model:**
- **Purpose:** Binds the value of HTML controls (input fields, text areas, etc.) to a variable in the
AngularJS scope, creating a two-way data binding between the view and the model.

- **Example:**

```html

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

<p>Your username is: {{username}}</p>

```

- **ng-required:**

- **Purpose:** Sets a field as required in a form. It adds validation to ensure that the input field is
not empty before the form can be submitted.

- **Example:**

```html

<form name="myForm">

<input type="text" ng-model="username" ng-required="true">

<span ng-show="myForm.username.$error.required">Username is required!</span>

</form>

```

c) **Validation in AngularJS:**

- **Overview:** AngularJS provides built-in directives and services to handle form validation. This
includes validating user input based on rules and displaying appropriate error messages.

**Key Components:**

- **Form Controls:** Elements like `<input>`, `<select>`, and `<textarea>` can be validated using
AngularJS directives such as `ng-required`, `ng-pattern`, `ng-minlength`, and `ng-maxlength`.

- **Validation States:** AngularJS sets form control properties such as `$valid`, `$invalid`, `$dirty`,
and `$pristine` to reflect the validation state of the form and its controls.

- **Error Messages:** Conditional display of error messages based on the validity of the form
controls. For example:

```html

<form name="myForm">
<input type="email" ng-model="email" ng-required="true" name="email">

<span ng-show="myForm.email.$error.required">Email is required!</span>

<span ng-show="myForm.email.$error.email">Invalid email address!</span>

</form>

```

**How It Works:**

- **Validation Directives:** Directives such as `ng-required`, `ng-pattern`, and `ng-minlength` are


used to define validation rules.

- **Model State:** The form and input elements track their own validation state, allowing you to
access these states and display feedback accordingly.

QP2

Here are concise explanations for each question:

a) **What is a Controller?**

- **Definition:** In AngularJS, a controller is a JavaScript function that is used to build the model
and handle business logic for a view. It initializes the scope variables, processes user inputs, and
defines functions that can be used in the view.

- **Purpose:** Manages the data and behavior of a part of the application, binding data to the
view and handling user interaction.

b) **Explain ng-click:**

- **Definition:** The `ng-click` directive in AngularJS binds an HTML element's click event to a
function in the controller.

- **Usage:** It allows you to execute a function or method when an element is clicked.

- **Example:**

```html

<button ng-click="showMessage()">Click me!</button>

```

c) **What is Currency Filter?**

- **Definition:** The `currency` filter in AngularJS formats a number as a currency string.


- **Usage:** It displays numbers in a currency format, including currency symbols, decimal points,
and thousands separators.

- **Example:**

```html

<p>{{ amount | currency }}</p>

```

d) **Explain Two-Way Data Binding:**

- **Definition:** Two-way data binding in AngularJS is a mechanism where changes in the model
automatically reflect in the view and vice versa.

- **Usage:** Allows synchronization of data between the model (JavaScript) and the view (HTML),
so that any change in the input field updates the model and changes in the model update the view.

- **Example:**

```html

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

<p>Hello, {{name}}!</p>

```

e) **What is Angular View?**

- **Definition:** In AngularJS, a view is a template (usually an HTML file) that displays data bound
to the model and is managed by a controller.

- **Purpose:** Represents the user interface part of the application, where data is presented and
user interactions occur.

f) **Explain $http Service:**

- **Definition:** The `$http` service in AngularJS is used to make HTTP requests to servers.

- **Usage:** Allows you to perform AJAX operations, retrieve or send data to a server.

- **Example:**

```javascript

$http.get('url').then(function(response) {

$scope.data = response.data;

});

```
g) **What is AJAX?**

- **Definition:** Asynchronous JavaScript and XML (AJAX) is a technique for creating asynchronous
web applications.

- **Purpose:** Allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes, without reloading the entire page.

h) **What is Dependency Injection?**

- **Definition:** Dependency Injection (DI) is a design pattern used to implement Inversion of


Control (IoC), allowing objects to be injected into a class or component rather than having it create
them internally.

- **Purpose:** Promotes loose coupling and increases modularity by allowing dependencies to be


injected from outside, making the code easier to test and maintain.

i) **Explain $timeout Service:**

- **Definition:** The `$timeout` service in AngularJS is similar to `setTimeout` in JavaScript. It


allows you to execute a function after a specified delay.

- **Usage:** It is used to schedule functions to run after a delay and automatically integrates with
AngularJS’s digest cycle.

- **Example:**

```javascript

$timeout(function() {

$scope.message = 'Updated after 2 seconds';

}, 2000);

```

j) **What is SPA?**

- **Definition:** A Single Page Application (SPA) is a type of web application that loads a single
HTML page and dynamically updates the content as the user interacts with the application.

- **Purpose:** Enhances user experience by providing a more fluid and responsive interface
without full page reloads.

Here are detailed answers to each question:


a) **How MVC Works in AngularJS:**

**MVC (Model-View-Controller) in AngularJS:**

- **Model:**

- **Definition:** Represents the data and business logic of the application.

- **In AngularJS:** The model is typically represented by the `$scope` object, which contains the
application's data and functions. This can also be enhanced using services and factories to handle
more complex data interactions.

- **Example:**

```javascript

app.controller('myCtrl', function($scope) {

$scope.greeting = 'Hello World!';

});

```

- **View:**

- **Definition:** Represents the user interface of the application. It displays data from the model
and provides a way for the user to interact with the application.

- **In AngularJS:** The view is defined using HTML templates with AngularJS directives such as
`ng-repeat`, `ng-bind`, and `ng-model`. These directives bind the model data to the view.

- **Example:**

```html

<div ng-controller="myCtrl">

<p>{{greeting}}</p>

</div>

```

- **Controller:**

- **Definition:** Acts as an intermediary between the Model and the View. It processes input,
updates the Model, and refreshes the View.

- **In AngularJS:** The controller is defined as a JavaScript function that initializes the `$scope`
object, defines functions, and handles user interactions.
- **Example:**

```javascript

app.controller('myCtrl', function($scope) {

$scope.greeting = 'Hello World!';

});

```

**How It Works Together:**

- The **Controller** initializes the **Model** (data) and provides methods to manipulate the
data.

- The **View** binds to the **Model** using AngularJS directives and displays the data.

- Any user input or changes in the **View** are processed by the **Controller**, which updates
the **Model** and consequently updates the **View**.

b) **Difference Between AngularJS Expression and JavaScript Expression:**

- **AngularJS Expression:**

- **Purpose:** Used within AngularJS templates to bind data to the view. AngularJS expressions
are evaluated in the context of the `$scope` object.

- **Syntax:** Enclosed in double curly braces `{{}}` or used with directives like `ng-bind`, `ng-
model`.

- **Example:**

```html

<p>{{user.name}}</p>

```

- **JavaScript Expression:**

- **Purpose:** Used in JavaScript code to perform operations, evaluate conditions, and handle
logic.

- **Syntax:** Standard JavaScript syntax without specific AngularJS delimiters.

- **Example:**

```javascript

var result = 5 + 3;
```

**Key Differences:**

- AngularJS expressions are limited in functionality compared to JavaScript expressions. They do not
support statements, functions, or complex logic.

- AngularJS expressions are automatically evaluated and updated in the view with the `$digest`
cycle.

c) **What is Scope Hierarchy? Explain with Example:**

- **Definition:** Scope hierarchy in AngularJS refers to the way `$scope` objects are organized in a
tree-like structure. Each scope inherits from its parent scope, allowing for hierarchical data binding.

- **Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

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

<script>

var app = angular.module('myApp', []);

app.controller('parentCtrl', function($scope) {

$scope.parentMessage = "Message from parent";

});

app.controller('childCtrl', function($scope) {

$scope.childMessage = "Message from child";

});

</script>

</head>

<body ng-controller="parentCtrl">

<p>{{parentMessage}}</p>

<div ng-controller="childCtrl">

<p>{{childMessage}}</p>
<p>{{parentMessage}}</p>

</div>

</body>

</html>

```

**Explanation:**

- The `parentCtrl` controller defines a scope with `parentMessage`.

- The `childCtrl` controller defines a scope with `childMessage`.

- The child scope inherits from the parent scope, so `childCtrl` can access `parentMessage` in
addition to its own scope data.

d) **AngularJS Program to Create a Service for Finding Factorial of a Number:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Factorial Service</title>

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

<script>

var app = angular.module('myApp', []);

app.service('factorialService', function() {

this.calculate = function(n) {

if (n <= 1) return 1;

return n * this.calculate(n - 1);

};

});

app.controller('myCtrl', function($scope, factorialService) {


$scope.number = null;

$scope.result = null;

$scope.calculateFactorial = function() {

$scope.result = factorialService.calculate($scope.number);

};

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Enter a number: <input type="number" ng-model="number"></p>

<button ng-click="calculateFactorial()">Calculate Factorial</button>

<p>Factorial: {{result}}</p>

</body>

</html>

```

**Explanation:**

- The `factorialService` provides a method `calculate` to compute the factorial of a number.

- The `myCtrl` controller uses this service to calculate the factorial based on user input.

e) **AngularJS Script to Display List of Games Stored in an Array on Click of Button Using ng-click:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Display Games</title>

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

<script>

var app = angular.module('myApp', []);


app.controller('myCtrl', function($scope) {

$scope.games = ['Soccer', 'Basketball', 'Tennis', 'Baseball'];

$scope.showGames = function() {

$scope.displayList = $scope.games;

};

});

</script>

</head>

<body ng-controller="myCtrl">

<button ng-click="showGames()">Show Games</button>

<ul>

<li ng-repeat="game in displayList">{{game}}</li>

</ul>

</body>

</html>

```

**Explanation:**

- The `showGames` function is triggered by the `ng-click` directive.

- It assigns the `games` array to `displayList`, which is then displayed in a list using `ng-repeat`.

Here are detailed answers to each question:

a) **Difference Between AngularJS and JavaScript:**

- **AngularJS:**

- **Framework:** AngularJS is a JavaScript framework developed by Google for building dynamic


single-page applications (SPAs).

- **Features:** Provides built-in support for two-way data binding, dependency injection,
directives, and templating.
- **Purpose:** Facilitates the development of structured, maintainable, and scalable web
applications with a declarative approach to UI and data binding.

- **Example:**

```html

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

<p>{{message}}</p>

</div>

```

- **JavaScript:**

- **Language:** JavaScript is a programming language used to create interactive effects and


manipulate the DOM on web pages.

- **Features:** Provides basic functionalities like variables, loops, conditionals, and functions.

- **Purpose:** Enables client-side scripting to enhance user interactions and perform various
operations on web pages.

- **Example:**

```javascript

document.getElementById("demo").innerHTML = "Hello World!";

```

**Key Differences:**

- AngularJS is a framework that provides structure and tools for building web applications, while
JavaScript is a general-purpose language used to create dynamic web content.

- AngularJS includes additional features like dependency injection and directives, which are not
natively available in JavaScript.

b) **Most Common Directives Used in AngularJS Applications:**

1. **ng-model:**

- **Purpose:** Binds the value of HTML controls (input, select, textarea) to a variable in the
AngularJS scope, allowing two-way data binding.

- **Example:**

```html
<input type="text" ng-model="name">

```

2. **ng-repeat:**

- **Purpose:** Iterates over a collection (array or object) and renders HTML for each item in the
collection.

- **Example:**

```html

<ul>

<li ng-repeat="item in items">{{item}}</li>

</ul>

```

3. **ng-if:**

- **Purpose:** Conditionally includes or excludes an HTML element based on an expression.

- **Example:**

```html

<div ng-if="isVisible">This is visible only if isVisible is true.</div>

```

4. **ng-click:**

- **Purpose:** Binds a click event to a function in the controller, allowing user interactions to
trigger methods.

- **Example:**

```html

<button ng-click="doSomething()">Click me</button>

```

c) **What is Module Life Cycle?**

- **Definition:** The module life cycle in AngularJS refers to the series of stages a module goes
through from creation to destruction. It involves initialization, configuration, and destruction phases.
**Key Stages:**

- **Creation:** The module is defined and registered with the AngularJS application using
`angular.module()`.

- **Configuration:** The module's configuration phase allows for setting up providers, services,
and routes before the application starts running.

- **Initialization:** AngularJS initializes the module, setting up controllers, directives, and services.

- **Destruction:** When the application is destroyed or a module is no longer needed, AngularJS


performs clean-up tasks.

**Example:**

```javascript

var app = angular.module('myApp', []);

app.config(function($provide) {

// Configuration logic here

});

app.run(function($rootScope) {

// Initialization logic here

});

```

d) **Program to Show the Use of ng-repeat:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>ng-repeat Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {
$scope.items = ['Apple', 'Banana', 'Cherry'];

});

</script>

</head>

<body ng-controller="myCtrl">

<ul>

<li ng-repeat="item in items">{{item}}</li>

</ul>

</body>

</html>

```

**Explanation:**

- The `ng-repeat` directive iterates over the `items` array and renders each item as a list element
(`<li>`).

e) **AngularJS Script to Display 10 Student Details in Table Format Using ng-repeat Directive:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Student Details</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.students = [

{ name: 'John Doe', age: 20, grade: 'A' },

{ name: 'Jane Smith', age: 22, grade: 'B' },

{ name: 'Alice Johnson', age: 21, grade: 'A' },


{ name: 'Bob Brown', age: 23, grade: 'C' },

{ name: 'Charlie Davis', age: 20, grade: 'B' },

{ name: 'David Wilson', age: 22, grade: 'A' },

{ name: 'Eve Adams', age: 21, grade: 'B' },

{ name: 'Frank Green', age: 23, grade: 'C' },

{ name: 'Grace Lee', age: 20, grade: 'A' },

{ name: 'Hannah Martinez', age: 22, grade: 'B' }

];

});

</script>

</head>

<body ng-controller="myCtrl">

<table border="1">

<thead>

<tr>

<th>Name</th>

<th>Age</th>

<th>Grade</th>

</tr>

</thead>

<tbody>

<tr ng-repeat="student in students">

<td>{{student.name}}</td>

<td>{{student.age}}</td>

<td>{{student.grade}}</td>

</tr>

</tbody>

</table>

</body>

</html>

```
**Explanation:**

- The `ng-repeat` directive iterates over the `students` array and displays each student's details in a
table format. Each student object has `name`, `age`, and `grade` properties that are displayed in the
respective columns.

Here are detailed answers for each question:

a) **Disadvantages of AngularJS:**

1. **Performance Issues:**

- **Description:** AngularJS can suffer from performance issues when handling large data sets or
complex DOM manipulations due to its two-way data binding and digest cycle.

- **Impact:** This can lead to slower rendering and responsiveness, especially in large
applications.

2. **Steep Learning Curve:**

- **Description:** AngularJS introduces several new concepts such as directives, dependency


injection, and scope, which can be challenging for beginners to learn and master.

- **Impact:** It requires a significant investment of time and effort to become proficient in


AngularJS.

3. **Complexity in Large Applications:**

- **Description:** Managing the structure and dependencies in large AngularJS applications can
become complex and hard to maintain.

- **Impact:** This can make it difficult to scale and refactor code effectively.

4. **Deprecated Status:**

- **Description:** AngularJS is no longer actively maintained and has been replaced by Angular
(Angular 2+), which offers improved performance and more modern features.

- **Impact:** Using AngularJS may result in missing out on the latest advancements and
improvements in the Angular ecosystem.

b) **Distinguish Between Factory, Service, and Provider:**


- **Factory:**

- **Purpose:** A factory is a function that returns an object or value. It is used to create and
configure services or objects in AngularJS.

- **Syntax:**

```javascript

app.factory('myFactory', function() {

var factory = {};

factory.getData = function() { return "data"; };

return factory;

});

```

- **Use Case:** When you need a simple object or service that does not require complex
configuration.

- **Service:**

- **Purpose:** A service is a constructor function that is instantiated with the `new` keyword. It is
used to create reusable components or services.

- **Syntax:**

```javascript

app.service('myService', function() {

this.getData = function() { return "data"; };

});

```

- **Use Case:** When you need to create a singleton service with shared state or behavior.

- **Provider:**

- **Purpose:** A provider is a more configurable way to define a service. It allows for


configuration during the module’s configuration phase.

- **Syntax:**

```javascript

app.provider('myProvider', function() {
this.$get = function() {

return { getData: function() { return "data"; } };

};

});

```

- **Use Case:** When you need to configure the service during the module's configuration phase
or when the service requires additional setup.

c) **Different Types of Form Events:**

- **ng-submit:**

- **Description:** Triggered when a form is submitted.

- **Usage:** Typically used to handle form submission.

- **Example:**

```html

<form ng-submit="submitForm()">

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

<button type="submit">Submit</button>

</form>

```

- **ng-change:**

- **Description:** Triggered when the value of an input field changes.

- **Usage:** Used to perform actions whenever the user modifies the input.

- **Example:**

```html

<input type="text" ng-model="inputData" ng-change="handleChange()">

```

- **ng-focus:**

- **Description:** Triggered when an input field gains focus.


- **Usage:** Used to perform actions when the user focuses on an input field.

- **Example:**

```html

<input type="text" ng-model="inputData" ng-focus="handleFocus()">

```

- **ng-blur:**

- **Description:** Triggered when an input field loses focus.

- **Usage:** Used to perform actions when the user moves focus away from the input field.

- **Example:**

```html

<input type="text" ng-model="inputData" ng-blur="handleBlur()">

```

d) **Explain $document Service, $log Service, and $rootScope Service in Brief:**

- **$document Service:**

- **Description:** A wrapper around the global `document` object. It provides a way to interact
with the DOM in a platform-independent manner.

- **Usage:** Used to manipulate the document or listen to document-level events.

- **Example:**

```javascript

app.controller('myCtrl', function($document) {

$document.on('click', function() {

console.log('Document clicked!');

});

});

```

- **$log Service:**

- **Description:** A service for logging messages to the browser console. It is useful for
debugging and tracking application behavior.
- **Usage:** Provides methods like `log()`, `info()`, `warn()`, and `error()`.

- **Example:**

```javascript

app.controller('myCtrl', function($log) {

$log.info('This is an informational message.');

});

```

- **$rootScope Service:**

- **Description:** The root scope of the AngularJS application. It is the parent object of all other
scopes and is available throughout the application.

- **Usage:** Used for sharing data or functions across controllers and directives.

- **Example:**

```javascript

app.controller('parentCtrl', function($rootScope) {

$rootScope.sharedData = 'This data is available globally.';

});

```

e) **Explain Custom Filter with Example:**

- **Definition:** Custom filters in AngularJS allow you to create reusable transformations on data
displayed in views. They can be used with the `|` (pipe) operator in expressions to format data.

- **Creating a Custom Filter:**

```javascript

var app = angular.module('myApp', []);

app.filter('reverse', function() {

return function(input) {

if (!input) return;

return input.split('').reverse().join('');
};

});

```

- **Using the Custom Filter in a View:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Custom Filter Example</title>

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

<script>

var app = angular.module('myApp', []);

app.filter('reverse', function() {

return function(input) {

if (!input) return;

return input.split('').reverse().join('');

};

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Original: {{text}}</p>

<p>Reversed: {{text | reverse}}</p>

</body>

</html>

```

**Explanation:**
- The custom filter `reverse` takes a string input, splits it into an array of characters, reverses the
array, and joins it back into a string.

- In the HTML view, `{{text | reverse}}` uses this custom filter to display the reversed version of the
`text` variable.

Here are detailed answers for each question:

a) **Explain Data Filter with Example:**

- **Definition:** Data filters in AngularJS are used to format or transform data displayed in views.
They take an input value and return a formatted or transformed value based on certain criteria.

- **Common Data Filters:**

- **`date`:** Formats dates according to a specified format.

- **`number`:** Formats numbers to a specific decimal precision.

- **`currency`:** Formats numbers as currency values.

- **Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Data Filter Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.date = new Date();

$scope.amount = 1234.56;

});

</script>

</head>
<body ng-controller="myCtrl">

<p>Date: {{date | date:'fullDate'}}</p>

<p>Amount: {{amount | currency:'$'}}</p>

<p>Number: {{amount | number:2}}</p>

</body>

</html>

```

**Explanation:**

- The `date` filter formats the `date` object into a readable date string using the 'fullDate' format.

- The `currency` filter formats the `amount` as a currency value with a dollar sign.

- The `number` filter formats the `amount` to two decimal places.

b) **What is Model Binding?**

- **Definition:** Model binding in AngularJS refers to the synchronization between the data model
and the view. It allows for automatic updates between the two, ensuring that any changes in the
model are reflected in the view and vice versa.

- **Two-Way Data Binding:**

- **Description:** AngularJS uses two-way data binding to keep the model and the view in sync.
When the model changes, the view is updated, and when the user interacts with the view, the model
is updated.

- **Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Model Binding Example</title>

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

<script>

var app = angular.module('myApp', []);


app.controller('myCtrl', function($scope) {

$scope.name = 'John';

});

</script>

</head>

<body ng-controller="myCtrl">

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

<p>Hello, {{name}}!</p>

</body>

</html>

```

**Explanation:**

- The `ng-model` directive binds the `name` property to the input field. Any change to the input
field updates the `name` property, and any change to the `name` property updates the text in the
paragraph.

c) **Explain Custom Validation:**

- **Definition:** Custom validation in AngularJS allows you to define your own validation rules for
form inputs beyond the built-in validators. This is useful when you need specific validation logic that
is not covered by default AngularJS validators.

- **Creating Custom Validation:**

- **Use Case:** Suppose you need to validate that a password contains both letters and numbers.

- **Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Custom Validation Example</title>

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

var app = angular.module('myApp', []);

app.directive('passwordValidator', function() {

return {

require: 'ngModel',

link: function(scope, element, attrs, ngModel) {

ngModel.$validators.passwordValidator = function(value) {

// Password must contain both letters and numbers

return /[a-zA-Z]/.test(value) && /\d/.test(value);

};

};

});

app.controller('myCtrl', function($scope) {

$scope.user = { password: '' };

});

</script>

</head>

<body ng-controller="myCtrl">

<form name="myForm">

<label for="password">Password:</label>

<input type="password" name="password" ng-model="user.password" password-validator>

<span ng-show="myForm.password.$error.passwordValidator">Password must contain both


letters and numbers.</span>

<button type="submit" ng-disabled="myForm.$invalid">Submit</button>

</form>

</body>

</html>

```
**Explanation:**

- The `passwordValidator` directive creates a custom validator for the password field. It checks if
the password contains both letters and numbers.

- The error message is displayed if the password does not meet the criteria.

QP3

Here are concise answers to each question:

a) **What is SPA?**

- **Definition:** SPA stands for Single Page Application. It is a web application that loads a single
HTML page and dynamically updates the content as the user interacts with the app, without
requiring a full page reload.

- **Advantages:** Provides a smoother user experience with faster navigation and reduced server
load.

b) **Explain ng-controller Directive:**

- **Definition:** The `ng-controller` directive in AngularJS specifies a controller for a part of the
HTML view. It creates a new scope and assigns the controller to that scope.

- **Example:**

```html

<div ng-controller="MyController">

<p>{{message}}</p>

</div>

```

**Explanation:** The controller named `MyController` will manage the scope within the `<div>`,
making variables like `message` available in the view.

c) **Write Any Two Features of AngularJS:**


1. **Two-Way Data Binding:** Automatically synchronizes data between the model and the view,
reducing the need for manual DOM updates.

2. **Dependency Injection:** Simplifies the process of injecting and managing dependencies in an


application, improving modularity and testability.

d) **Explain Two-Way Data Binding:**

- **Definition:** Two-way data binding in AngularJS ensures that changes in the model
automatically update the view and changes in the view automatically update the model.

- **Example:**

```html

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

<p>Hello, {{name}}!</p>

```

**Explanation:** Changes to the input field automatically update `name` in the model, and
changes to `name` in the model update the text in the paragraph.

e) **What is Controller?**

- **Definition:** A controller in AngularJS is a JavaScript function that initializes and maintains the
application data and logic. It is used to control the data-binding and user interactions in the view.

- **Example:**

```javascript

app.controller('MyController', function($scope) {

$scope.message = "Hello, World!";

});

```

f) **Explain $http Services:**

- **Definition:** The `$http` service in AngularJS is used to make HTTP requests to a server,
allowing you to fetch or send data asynchronously.

- **Example:**
```javascript

app.controller('MyController', function($scope, $http) {

$http.get('api/data').then(function(response) {

$scope.data = response.data;

});

});

```

g) **Explain Uppercase Filter:**

- **Definition:** The `uppercase` filter converts text to uppercase in the view.

- **Example:**

```html

<p>{{name | uppercase}}</p>

```

**Explanation:** The `name` variable is displayed in uppercase in the paragraph.

h) **What is Dependency Injection?**

- **Definition:** Dependency Injection (DI) is a design pattern used in AngularJS to manage and
inject dependencies (services, factories) into components (controllers, directives) rather than having
components create their own dependencies.

- **Purpose:** Promotes modularity and makes testing easier.

i) **Explain $timeout Service:**

- **Definition:** The `$timeout` service is a wrapper around the JavaScript `setTimeout` function.
It allows you to execute code after a specified delay and integrates with AngularJS’s digest cycle.

- **Example:**

```javascript

app.controller('MyController', function($scope, $timeout) {

$timeout(function() {
$scope.message = "Updated after 2 seconds!";

}, 2000);

});

```

j) **Explain Custom Validation:**

- **Definition:** Custom validation in AngularJS allows you to define your own validation rules for
form inputs beyond the built-in validators.

- **Example:**

```javascript

app.directive('passwordValidator', function() {

return {

require: 'ngModel',

link: function(scope, element, attrs, ngModel) {

ngModel.$validators.passwordValidator = function(value) {

return /[a-zA-Z]/.test(value) && /\d/.test(value);

};

};

});

```

**Explanation:** The `passwordValidator` directive checks if a password contains both letters and
numbers.

Here are detailed answers for each question:

a) **Explain Most Common Directives Used in AngularJS:**

- **`ng-model`:**

- **Description:** Binds the value of HTML controls (e.g., input, select) to a property on the
scope.
- **Example:**

```html

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

<p>Welcome, {{username}}!</p>

```

- **`ng-repeat`:**

- **Description:** Repeats a portion of HTML for each item in an array or object. Useful for
displaying lists and tables.

- **Example:**

```html

<ul>

<li ng-repeat="item in items">{{item}}</li>

</ul>

```

- **`ng-if`:**

- **Description:** Conditionally includes or excludes a portion of HTML based on the expression's


truthiness.

- **Example:**

```html

<p ng-if="showMessage">This message is shown if `showMessage` is true.</p>

```

- **`ng-show` and `ng-hide`:**

- **Description:** Toggles the visibility of HTML elements based on the expression's truthiness.

- **Example:**

```html

<p ng-show="isVisible">This text is visible if `isVisible` is true.</p>

<p ng-hide="isHidden">This text is hidden if `isHidden` is true.</p>

```
- **`ng-click`:**

- **Description:** Binds an expression to the click event of an element.

- **Example:**

```html

<button ng-click="incrementCounter()">Click me!</button>

```

b) **Explain MVC Architecture in Detail:**

- **Model-View-Controller (MVC) Architecture:**

- **Model:**

- **Description:** Represents the data and business logic of the application. It is responsible for
retrieving, storing, and updating data.

- **Example:** In AngularJS, this might include services or factories that interact with APIs and
data sources.

- **View:**

- **Description:** Represents the user interface (UI) of the application. It displays the data from
the model and provides an interface for user interaction.

- **Example:** In AngularJS, this would be the HTML templates and directives that bind to the
model.

- **Controller:**

- **Description:** Acts as an intermediary between the model and the view. It processes user
input, manipulates the model, and updates the view.

- **Example:** In AngularJS, controllers manage the scope and provide data and behavior to the
view.

**Example Workflow:**

- The **view** sends user input to the **controller**.

- The **controller** processes this input, updates the **model**, and may trigger updates to the
**view**.

- The **model** changes trigger updates to the **view** through data binding.
c) **Explain Built-in Services of AngularJS:**

- **`$http`:**

- **Description:** Provides methods for making HTTP requests (e.g., GET, POST) to interact with
backend services.

- **Example:**

```javascript

$http.get('/api/data').then(function(response) {

$scope.data = response.data;

});

```

- **`$timeout`:**

- **Description:** Wrapper for `setTimeout` that integrates with AngularJS’s digest cycle. Allows
you to delay the execution of code.

- **Example:**

```javascript

$timeout(function() {

$scope.message = "Updated after 2 seconds!";

}, 2000);

```

- **`$location`:**

- **Description:** Provides access to the URL in the browser and allows manipulation of the URL
and the browser history.

- **Example:**

```javascript

$location.path('/newPath');

```

- **`$filter`:**
- **Description:** Provides methods for formatting data, such as strings, dates, and numbers.

- **Example:**

```javascript

var formattedDate = $filter('date')(new Date(), 'fullDate');

```

- **`$log`:**

- **Description:** Provides methods for logging messages to the browser console (e.g., `log`,
`info`, `warn`, `error`).

- **Example:**

```javascript

$log.info('This is an informational message.');

```

d) **Write an AngularJS Program to Create a Service for Finding the Factorial of a Number:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Factorial Service Example</title>

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

<script>

var app = angular.module('myApp', []);

app.service('factorialService', function() {

this.calculate = function(n) {

if (n === 0) return 1;

return n * this.calculate(n - 1);

};

});
app.controller('myCtrl', function($scope, factorialService) {

$scope.factorial = function() {

$scope.result = factorialService.calculate($scope.number);

};

});

</script>

</head>

<body ng-controller="myCtrl">

<input type="number" ng-model="number">

<button ng-click="factorial()">Calculate Factorial</button>

<p>Factorial: {{result}}</p>

</body>

</html>

```

**Explanation:**

- The `factorialService` service contains a `calculate` method to compute the factorial of a number
recursively.

- The `myCtrl` controller uses this service to compute and display the factorial of the number
entered by the user.

e) **Write an AngularJS Program for Using $filter Service:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>$filter Service Example</title>

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

<script>

var app = angular.module('myApp', []);


app.controller('myCtrl', function($scope, $filter) {

$scope.date = new Date();

$scope.number = 1234.5678;

$scope.formattedDate = $filter('date')($scope.date, 'fullDate');

$scope.formattedNumber = $filter('number')($scope.number, 2);

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Original Date: {{date}}</p>

<p>Formatted Date: {{formattedDate}}</p>

<p>Original Number: {{number}}</p>

<p>Formatted Number: {{formattedNumber}}</p>

</body>

</html>

```

**Explanation:**

- The `$filter` service is used to format a date and number. The `date` filter formats the date, and
the `number` filter formats the number to two decimal places.

Here are detailed answers for each question:

a) **Give Difference Between AngularJS and JavaScript:**

- **AngularJS:**

- **Description:** AngularJS is a JavaScript framework developed by Google for building dynamic


single-page applications (SPAs). It extends HTML with additional attributes and provides powerful
features such as two-way data binding, dependency injection, and directives.

- **Features:**
- **Two-Way Data Binding:** Automatically synchronizes data between the model and the view.

- **Directives:** Custom HTML elements or attributes that extend HTML’s capabilities.

- **Dependency Injection:** Provides a way to inject services and other dependencies into
components.

- **JavaScript:**

- **Description:** JavaScript is a versatile scripting language used for creating interactive and
dynamic content on websites. It is a core technology of the web alongside HTML and CSS.

- **Features:**

- **General-Purpose:** Used for a wide range of programming tasks, from simple scripts to
complex applications.

- **Event-Driven:** Supports event handling and manipulation of DOM elements.

- **Non-Framework Specific:** Can be used with or without frameworks/libraries.

**Comparison Summary:**

- **AngularJS** is a framework that simplifies building complex web applications by providing


structure and features like data binding and dependency injection.

- **JavaScript** is a language that can be used in a variety of contexts, including server-side and
client-side programming, without the built-in functionalities provided by frameworks like AngularJS.

b) **Explain the Ways to Implement Custom Directives in AngularJS:**

- **Definition:** Custom directives in AngularJS allow you to create reusable components and
behavior that can be applied to HTML elements.

- **Ways to Implement:**

1. **Element Directives:** Create a new HTML element.

```javascript

app.directive('myElement', function() {

return {

restrict: 'E',

template: '<p>This is a custom element directive.</p>'

};
});

```

**Usage:**

```html

<my-element></my-element>

```

2. **Attribute Directives:** Enhance existing HTML elements with custom behavior.

```javascript

app.directive('myAttribute', function() {

return {

restrict: 'A',

link: function(scope, element, attrs) {

element.css('color', 'red');

};

});

```

**Usage:**

```html

<div my-attribute>This text will be red.</div>

```

3. **Class Directives:** Apply behavior to elements based on a CSS class.

```javascript

app.directive('myClass', function() {

return {

restrict: 'C',

link: function(scope, element, attrs) {

element.on('click', function() {

alert('Element clicked!');
});

};

});

```

**Usage:**

```html

<div class="my-class">Click me!</div>

```

4. **Comment Directives:** Add behavior to elements using comments.

```javascript

app.directive('myComment', function() {

return {

restrict: 'M',

link: function(scope, element, attrs) {

element.text('This is a custom comment directive.');

};

});

```

**Usage:**

```html

<!-- directive: myComment -->

```

c) **Write Advantage of Creating Modules:**

- **Modularity:** Modules allow you to break down your application into smaller, manageable,
and reusable components. This modular approach helps in organizing the codebase, improving
maintainability, and enhancing the scalability of the application.
- **Separation of Concerns:** By using modules, you can separate different functionalities of the
application into distinct units, each with its own responsibilities. This makes it easier to manage
dependencies and reduces the complexity of the application.

- **Code Reusability:** Modules can be reused across different parts of the application or even in
different projects. This promotes code reuse and reduces redundancy.

d) **Write a Program That Can Show the Use of `ng-repeat`:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>ng-repeat Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.items = ['Apple', 'Banana', 'Cherry'];

});

</script>

</head>

<body ng-controller="myCtrl">

<ul>

<li ng-repeat="item in items">{{item}}</li>

</ul>

</body>

</html>

```

**Explanation:**

- The `ng-repeat` directive iterates over the `items` array and creates a `<li>` element for each item,
displaying the item’s value.
e) **Write a Program to Demonstrate Use of Factory Function:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Factory Function Example</title>

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

<script>

var app = angular.module('myApp', []);

app.factory('mathService', function() {

return {

add: function(a, b) {

return a + b;

},

subtract: function(a, b) {

return a - b;

};

});

app.controller('myCtrl', function($scope, mathService) {

$scope.num1 = 5;

$scope.num2 = 3;

$scope.sum = mathService.add($scope.num1, $scope.num2);

$scope.difference = mathService.subtract($scope.num1, $scope.num2);

});

</script>
</head>

<body ng-controller="myCtrl">

<p>Sum: {{sum}}</p>

<p>Difference: {{difference}}</p>

</body>

</html>

```

**Explanation:**

- The `mathService` factory provides methods for addition and subtraction.

- The `myCtrl` controller uses this service to perform calculations and display the results.

Here are detailed answers for each question:

a) **What is the Difference Between `$scope` and Scope?**

- **`$scope`:**

- **Definition:** `$scope` is a built-in AngularJS service that provides the binding between the
view (HTML) and the model (JavaScript). It is used within controllers to hold and manage the data
and functions that are shared between the view and the controller.

- **Characteristics:**

- **Per-Controller Scope:** `$scope` is specific to the controller in which it is defined and is


created when the controller is instantiated.

- **Hierarchy:** `$scope` is part of a hierarchical structure. Child scopes can inherit properties
from parent scopes.

- **Scope:**

- **Definition:** The term "scope" in AngularJS refers to the concept of the scope object used to
bind data between the controller and the view. It is a general term and encompasses both `$scope`
and its child scopes.

- **Characteristics:**

- **General Term:** "Scope" can refer to any scope object, including `$scope`, `$rootScope`, and
child scopes.
**Summary:**

- `$scope` is the specific service provided by AngularJS for data binding in controllers.

- "Scope" is a broader term referring to any object that serves as a binding context between the
view and the controller, including `$scope`.

b) **Write a Program to Create a Service to Calculate the Area of a Circle:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Circle Area Service Example</title>

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

<script>

var app = angular.module('myApp', []);

app.service('circleService', function() {

this.calculateArea = function(radius) {

return Math.PI * radius * radius;

};

});

app.controller('myCtrl', function($scope, circleService) {

$scope.radius = 5;

$scope.area = circleService.calculateArea($scope.radius);

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Radius: <input type="number" ng-model="radius" ng-change="area =


circleService.calculateArea(radius)"></p>
<p>Area of Circle: {{area}}</p>

</body>

</html>

```

**Explanation:**

- The `circleService` service provides a method `calculateArea` to compute the area of a circle given
its radius.

- The `myCtrl` controller uses this service to calculate and display the area of the circle.

c) **Explain Life Cycle of a Module:**

- **Definition:** The life cycle of an AngularJS module refers to the sequence of stages that a
module goes through from its creation to its destruction.

- **Stages:**

1. **Initialization:** When the AngularJS application starts, the module is initialized. This involves
loading the module configuration and setting up dependencies.

2. **Configuration:** During this stage, the module’s configuration block is executed. This block is
used to configure the module, such as setting up routing, providers, and other configuration settings.

3. **Run Block:** After configuration, the module’s run block is executed. This block is used for
application initialization tasks such as setting up services, initializing data, or configuring the
application state.

4. **Compilation:** AngularJS compiles the HTML templates by processing directives,


expressions, and bindings. This stage involves converting the HTML into a dynamic view.

5. **Digest Cycle:** AngularJS performs the digest cycle to monitor changes in the application
state and update the view accordingly.

6. **Destruction:** When the application or module is destroyed (e.g., on navigation away from
the view), AngularJS cleans up and removes any resources or event listeners associated with the
module.

d) **Write a Program to Display Name, Qualification, and Address Using MVC Architecture:**

```html
<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>MVC Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.person = {

name: 'John Doe',

qualification: 'Bachelor of Science',

address: '123 Main Street, Anytown'

};

});

</script>

</head>

<body ng-controller="myCtrl">

<h2>Person Details</h2>

<p>Name: {{person.name}}</p>

<p>Qualification: {{person.qualification}}</p>

<p>Address: {{person.address}}</p>

</body>

</html>

```

**Explanation:**

- The `myCtrl` controller manages the data model `person`, which includes `name`, `qualification`,
and `address`.

- The view displays this data using AngularJS’s data binding.


e) **Explain `$document` Service, `$log` Service, and `$rootScope` Service in Brief:**

- **`$document` Service:**

- **Description:** Provides access to the native DOM document object. It allows interaction with
the document as a whole, such as manipulating or accessing global properties.

- **Example Usage:**

```javascript

app.controller('myCtrl', function($scope, $document) {

$document[0].title = "New Title";

});

```

- **`$log` Service:**

- **Description:** Provides methods for logging messages to the browser console. It includes
methods like `log`, `info`, `warn`, and `error`.

- **Example Usage:**

```javascript

app.controller('myCtrl', function($scope, $log) {

$log.info('This is an info message.');

$log.error('This is an error message.');

});

```

- **`$rootScope` Service:**

- **Description:** Acts as a parent object for all `$scope` objects created in the application. It
provides a way to share data and methods across all controllers and directives.

- **Example Usage:**

```javascript

app.run(function($rootScope) {

$rootScope.globalValue = "This is a global value";

});
app.controller('myCtrl', function($scope, $rootScope) {

$scope.localValue = $rootScope.globalValue;

});

```

**Summary:**

- **`$document`** is used for direct DOM manipulations.

- **`$log`** provides a logging mechanism.

- **`$rootScope`** serves as a global scope shared across controllers and directives.

Here are the detailed answers for each question:

a) **Data Binding:**

- **Definition:** Data binding in AngularJS is the process of synchronizing data between the model
(JavaScript variables) and the view (HTML). It allows automatic updates of the view when the model
changes and vice versa.

- **Types of Data Binding:**

1. **One-Way Data Binding:** Updates the view when the model changes, but not the other way
around. This is commonly used with AngularJS expressions and filters.

```html

<p>{{message}}</p>

```

- **Explanation:** If `message` in the model changes, the view will automatically update to
reflect the new value.

2. **Two-Way Data Binding:** Allows changes in the view to be reflected in the model and vice
versa. This is achieved using the `ng-model` directive.

```html

<input type="text" ng-model="user.name">

<p>Hello, {{user.name}}!</p>

```
- **Explanation:** When the user types into the input field, `user.name` in the model is
updated, and the view is updated automatically.

- **Benefits:**

- **Automatic Synchronization:** Reduces the need for manual DOM manipulation.

- **Simplifies Code:** Makes it easier to maintain and understand the application's data flow.

b) **`ng new`, `ng update`:**

- **`ng new`:**

- **Definition:** `ng new` is a command used in Angular CLI to create a new Angular application.
It sets up a new project with a default configuration and creates a directory structure for the
application.

- **Example Usage:**

```bash

ng new my-angular-app

```

- **Explanation:** This command generates a new Angular project named `my-angular-app` with
all the default Angular configuration files and directories.

- **`ng update`:**

- **Definition:** `ng update` is a command used to update Angular and its dependencies to the
latest versions. It helps in keeping the project up-to-date with the latest Angular features and bug
fixes.

- **Example Usage:**

```bash

ng update @angular/cli @angular/core

```

- **Explanation:** This command updates Angular CLI and Angular Core to the latest versions. It
also handles migration tasks and makes necessary changes to the project configuration.

c) **`angular.module`:**
- **Definition:** `angular.module` is a method in AngularJS used to create or retrieve AngularJS
modules. Modules are containers for different parts of an AngularJS application, such as controllers,
services, directives, and filters.

- **Syntax and Usage:**

1. **Creating a New Module:**

```javascript

var app = angular.module('myApp', []);

```

- **Explanation:** Creates a new AngularJS module named `myApp`. The empty array `[]`
indicates that there are no dependencies.

2. **Retrieving an Existing Module:**

```javascript

var app = angular.module('myApp');

```

- **Explanation:** Retrieves the existing module `myApp`. This can be used to configure the
module or add components like controllers and services.

- **Benefits:**

- **Organization:** Helps in organizing application code into modular units.

- **Dependency Management:** Facilitates managing and injecting dependencies between


different parts of the application.

QP4

Here are concise answers for each question:

a) **What is AngularJS?**

- **Definition:** AngularJS is a JavaScript framework developed by Google for building dynamic


single-page applications (SPAs). It extends HTML with additional features such as data binding,
directives, and dependency injection to create interactive and efficient web applications.
b) **What is SPA?**

- **Definition:** SPA stands for Single Page Application. It is a type of web application that loads a
single HTML page and dynamically updates the content as the user interacts with the app, without
requiring a full page reload. This provides a more fluid and responsive user experience.

c) **Write the Syntax of Building Blocks of AngularJS:**

- **Module:**

```javascript

var app = angular.module('myApp', []);

```

- **Controller:**

```javascript

app.controller('myCtrl', function($scope) {

$scope.message = 'Hello, World!';

});

```

- **Directive:**

```javascript

app.directive('myDirective', function() {

return {

restrict: 'E',

template: '<p>This is a directive</p>'

};

});

```

- **Service:**

```javascript
app.service('myService', function() {

this.sayHello = function() {

return 'Hello!';

};

});

```

- **Filter:**

```javascript

app.filter('customFilter', function() {

return function(input) {

return input.toUpperCase();

};

});

```

d) **What is Data Binding in AngularJS?**

- **Definition:** Data binding in AngularJS is the automatic synchronization of data between the
model and the view. It allows the view to reflect changes in the model and vice versa, eliminating the
need for manual DOM manipulation.

e) **Explain `ng-bind` Directive with Example:**

- **Definition:** The `ng-bind` directive binds the value of a scope variable to the text content of
an HTML element, replacing any existing text.

- **Syntax:**

```html

<span ng-bind="expression"></span>

```
- **Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.message = 'Hello, World!';

});

</script>

</head>

<body ng-controller="myCtrl">

<p ng-bind="message"></p>

</body>

</html>

```

- **Explanation:** The `ng-bind` directive binds the `message` variable to the `<p>` element,
displaying "Hello, World!".

f) **How to Create Controller in AngularJS?**

- **Definition:** A controller in AngularJS is created using the `controller` method on an AngularJS


module. It manages the scope of the view and contains the logic for the application.

- **Syntax:**

```javascript

app.controller('controllerName', function($scope) {

$scope.variable = 'value';

});
```

- **Example:**

```javascript

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.message = 'Hello from Controller!';

});

```

g) **What is the Difference Between `$scope` and `scope`?**

- **`$scope`:**

- **Definition:** `$scope` is a built-in AngularJS object used in controllers and directives to


provide a context for binding data between the view and the model.

- **Characteristics:** It is specific to controllers and directives, managing data and functions


within that scope.

- **`scope`:**

- **Definition:** The term `scope` generally refers to any scope object in AngularJS, including
`$scope`, `$rootScope`, and child scopes.

- **Characteristics:** It represents the hierarchical structure of scopes and can be used to


describe any context where data binding occurs.

h) **Explain Date Filter with Syntax & Example:**

- **Definition:** The date filter in AngularJS formats dates according to the specified format. It can
be used in views to display dates in a user-friendly manner.

- **Syntax:**

```html

{{ dateExpression | date:format }}

```
- **Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.currentDate = new Date();

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Current Date: {{ currentDate | date:'fullDate' }}</p>

</body>

</html>

```

- **Explanation:** The date filter formats `currentDate` using the `'fullDate'` format, displaying it as
"Saturday, September 2, 2024" (depending on the locale).

i) **What is `$http` Service?**

- **Definition:** The `$http` service in AngularJS is used for making AJAX requests to servers. It
provides methods to interact with HTTP APIs and handles responses, including JSON and text data.

- **Syntax:**

```javascript

$http({

method: 'GET',
url: 'api/endpoint'

}).then(function(response) {

// Success callback

console.log(response.data);

}, function(error) {

// Error callback

console.error(error);

});

```

- **Example:**

```javascript

app.controller('myCtrl', function($scope, $http) {

$http.get('https://api.example.com/data')

.then(function(response) {

$scope.data = response.data;

}, function(error) {

console.error(error);

});

});

```

j) **What is AngularJS Factory?**

- **Definition:** A factory in AngularJS is a design pattern used to create services. It is a function


that returns an object or a value and can be used to define reusable logic and data across an
application.

- **Syntax:**

```javascript

app.factory('factoryName', function() {

return {
methodName: function() {

// Logic here

};

});

```

- **Example:**

```javascript

var app = angular.module('myApp', []);

app.factory('mathFactory', function() {

return {

add: function(a, b) {

return a + b;

};

});

app.controller('myCtrl', function($scope, mathFactory) {

$scope.result = mathFactory.add(5, 3);

});

```

- **Explanation:** The `mathFactory` provides an `add` method for addition. This factory is
injected into the controller to use its functionality.

Here are detailed answers for each question:

a) **Explain the Difference Between AngularJS and JavaScript:**


- **JavaScript:**

- **Definition:** JavaScript is a programming language used to create interactive and dynamic


content on websites. It is a fundamental language for web development and runs in the browser or
on the server using environments like Node.js.

- **Features:**

- **General-purpose:** Can be used for a wide range of programming tasks.

- **Imperative and Object-Oriented:** Supports imperative, functional, and object-oriented


programming paradigms.

- **Direct DOM Manipulation:** Interacts directly with the Document Object Model (DOM) for
updating content on web pages.

- **AngularJS:**

- **Definition:** AngularJS is a JavaScript framework developed by Google for building dynamic


web applications. It extends JavaScript by adding features such as data binding, directives, and
dependency injection.

- **Features:**

- **Framework:** Provides a structured approach to building web applications.

- **Declarative Programming:** Uses declarative syntax with HTML to define the application's UI
and behavior.

- **Two-Way Data Binding:** Automatically synchronizes data between the model and the view.

- **Dependency Injection:** Manages dependencies and services in a modular way.

**Summary:**

- **JavaScript** is the core language used for client-side scripting.

- **AngularJS** is a framework that builds on JavaScript to provide additional tools and structure
for developing complex applications.

b) **What is a Module? Write Advantages of Modules:**

- **Definition:** In AngularJS, a module is a container for different parts of an application, such as


controllers, services, directives, and filters. It helps in organizing and structuring the application into
reusable components.

- **Syntax to Create a Module:**


```javascript

var app = angular.module('myApp', []);

```

- **Advantages of Modules:**

1. **Organization:** Modules help in organizing code into manageable and reusable pieces,
making the application more modular and maintainable.

2. **Dependency Management:** Modules can define dependencies on other modules, allowing


for better management of application dependencies.

3. **Encapsulation:** Each module encapsulates its own components, reducing the risk of name
conflicts and improving code clarity.

4. **Lazy Loading:** Modules can be loaded on demand, which can improve the performance of
the application by loading only the necessary parts.

c) **What Are the Different Forms of Form Events?**

- **Different Forms of Form Events:**

1. **`ng-submit`:** Triggered when a form is submitted. It can be used to handle form submission
and validation.

```html

<form ng-submit="submitForm()">

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

<button type="submit">Submit</button>

</form>

```

2. **`ng-change`:** Triggered when the value of an input field changes. It is useful for executing
logic when the input value is modified.

```html

<input type="text" ng-model="data" ng-change="updateData()">

```
3. **`ng-focus` and `ng-blur`:** Triggered when an input field gains or loses focus, respectively.
Useful for handling focus-related actions.

```html

<input type="text" ng-model="data" ng-focus="onFocus()" ng-blur="onBlur()">

```

4. **`ng-keyup` and `ng-keydown`:** Triggered when a key is pressed down or released in an


input field.

```html

<input type="text" ng-model="data" ng-keyup="handleKeyUp($event)">

```

d) **Write AngularJS Program for Multiplication of Two Numbers:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Multiplication Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.num1 = 0;

$scope.num2 = 0;

$scope.result = 0;

$scope.multiply = function() {

$scope.result = $scope.num1 * $scope.num2;

};

});
</script>

</head>

<body ng-controller="myCtrl">

<p>Number 1: <input type="number" ng-model="num1"></p>

<p>Number 2: <input type="number" ng-model="num2"></p>

<button ng-click="multiply()">Multiply</button>

<p>Result: {{result}}</p>

</body>

</html>

```

**Explanation:** This program uses AngularJS to multiply two numbers entered by the user and
display the result when a button is clicked.

e) **Write an AngularJS Program to Create Service for Finding Factorial of a Given Number:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Factorial Service Example</title>

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

<script>

var app = angular.module('myApp', []);

app.service('factorialService', function() {

this.calculateFactorial = function(n) {

if (n === 0) return 1;

return n * this.calculateFactorial(n - 1);

};

});
app.controller('myCtrl', function($scope, factorialService) {

$scope.number = 0;

$scope.factorial = 1;

$scope.computeFactorial = function() {

$scope.factorial = factorialService.calculateFactorial($scope.number);

};

});

</script>

</head>

<body ng-controller="myCtrl">

<p>Enter a number: <input type="number" ng-model="number"></p>

<button ng-click="computeFactorial()">Calculate Factorial</button>

<p>Factorial: {{factorial}}</p>

</body>

</html>

```

**Explanation:** This program uses an AngularJS service (`factorialService`) to calculate the


factorial of a given number. The `myCtrl` controller calls this service to perform the computation and
display the result.

Here are detailed answers for each question:

a) **Explain AngularJS Data Binding:**

- **Definition:** Data binding in AngularJS is a feature that automatically synchronizes data


between the model (JavaScript variables) and the view (HTML). It ensures that changes in the model
are reflected in the view and vice versa, providing a seamless user experience and reducing the need
for manual DOM manipulation.

- **Types of Data Binding:**


1. **One-Way Data Binding:** Updates the view when the model changes. AngularJS expressions,
such as `{{ expression }}`, use one-way data binding to display data in the view.

```html

<p>{{ message }}</p>

```

- **Explanation:** If `message` in the model changes, the view automatically updates to reflect
the new value.

2. **Two-Way Data Binding:** Synchronizes data between the model and the view. This is
achieved using the `ng-model` directive, which binds input fields to scope variables.

```html

<input type="text" ng-model="user.name">

<p>Hello, {{ user.name }}!</p>

```

- **Explanation:** Any change made in the input field updates `user.name` in the model, and
changes in the model are reflected in the view.

- **Benefits:**

- **Automatic Updates:** Reduces the need for manual DOM manipulation and ensures that the
view and model remain in sync.

- **Simplified Code:** Makes the code easier to maintain and understand, as data binding
automatically handles updates between the model and the view.

b) **Explain Scope Hierarchy in Detail:**

- **Definition:** Scope hierarchy in AngularJS refers to the hierarchical structure of scope objects
within an AngularJS application. Scopes are used to bind data and functions between controllers,
directives, and the view.

- **Types of Scopes:**

1. **Root Scope (`$rootScope`):** The top-level scope available throughout the application. It is a
global scope shared by all controllers and directives.

```javascript

app.controller('mainCtrl', function($rootScope) {
$rootScope.globalVariable = 'I am global';

});

```

2. **Child Scope:** Scopes created within controllers or directives. These scopes inherit
properties from their parent scope but can also define their own properties and functions.

```javascript

app.controller('childCtrl', function($scope) {

$scope.childVariable = 'I am a child';

});

```

3. **Isolated Scope:** Used in directives to create a scope that does not inherit from its parent
scope. It is useful for creating reusable components.

```javascript

app.directive('myDirective', function() {

return {

scope: {

isolatedVar: '='

},

template: '<p>{{ isolatedVar }}</p>'

};

});

```

- **Scope Hierarchy Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

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

<script>
var app = angular.module('myApp', []);

app.controller('parentCtrl', function($scope) {

$scope.parentData = 'Data from Parent';

});

app.controller('childCtrl', function($scope) {

$scope.childData = 'Data from Child';

});

</script>

</head>

<body ng-controller="parentCtrl">

<p>{{ parentData }}</p>

<div ng-controller="childCtrl">

<p>{{ childData }}</p>

</div>

</body>

</html>

```

- **Explanation:** In this example, `parentData` is available in the parent scope, while `childData`
is available in the child scope. The child scope has access to the parent scope but not vice versa.

c) **Create a Hello World Application Program Using AngularJS:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>Hello World Example</title>

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

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.message = 'Hello, World!';

});

</script>

</head>

<body ng-controller="myCtrl">

<p>{{ message }}</p>

</body>

</html>

```

**Explanation:** This simple AngularJS application uses a module and controller to bind a message
to the view, displaying "Hello, World!" on the page.

d) **Explain Lower-Case and Upper-Case Filters with Example:**

- **Lower-Case Filter:**

- **Definition:** The `lowercase` filter converts a string to lower case.

- **Syntax:**

```html

{{ expression | lowercase }}

```

- **Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

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

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.text = 'HELLO WORLD';

});

</script>

</head>

<body ng-controller="myCtrl">

<p>{{ text | lowercase }}</p>

</body>

</html>

```

- **Explanation:** The `lowercase` filter converts "HELLO WORLD" to "hello world".

- **Upper-Case Filter:**

- **Definition:** The `uppercase` filter converts a string to upper case.

- **Syntax:**

```html

{{ expression | uppercase }}

```

- **Example:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.text = 'hello world';

});
</script>

</head>

<body ng-controller="myCtrl">

<p>{{ text | uppercase }}</p>

</body>

</html>

```

- **Explanation:** The `uppercase` filter converts "hello world" to "HELLO WORLD".

e) **Write an AngularJS Program for `ng-copy` and `ng-paste` Events:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>ng-copy and ng-paste Example</title>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.copiedText = '';

$scope.pastedText = '';

$scope.handleCopy = function() {

alert('Text copied: ' + $scope.copiedText);

};

$scope.handlePaste = function() {

alert('Text pasted: ' + $scope.pastedText);

};
});

</script>

</head>

<body ng-controller="myCtrl">

<p>Copy the text below:</p>

<input type="text" ng-model="copiedText" ng-copy="handleCopy()" placeholder="Type and copy


text here">

<p>Paste the text here:</p>

<input type="text" ng-model="pastedText" ng-paste="handlePaste()" placeholder="Paste text


here">

</body>

</html>

```

**Explanation:** This program uses `ng-copy` to trigger an alert when text is copied and `ng-paste`
to trigger an alert when text is pasted into the input fields.

Here are detailed answers for each question:

a) **Explain the MVC Architecture:**

- **Definition:** The MVC (Model-View-Controller) architecture is a design pattern used in


software development to separate an application into three interconnected components. This
separation helps manage complex applications by organizing code and improving maintainability.

- **Components:**

1. **Model:**

- **Definition:** Represents the data and business logic of the application. It is responsible for
retrieving, processing, and storing data.

- **Functions:** Updates and manipulates data, notifies the view of changes.

- **Example:** In a web application, the model might interact with a database or API to fetch
and update data.
2. **View:**

- **Definition:** Represents the user interface (UI) of the application. It displays the data from
the model to the user and updates the UI based on user interactions.

- **Functions:** Renders data, handles user input, and updates the display when the model
changes.

- **Example:** HTML templates or UI components that present data to the user.

3. **Controller:**

- **Definition:** Acts as an intermediary between the model and the view. It processes user
input, interacts with the model, and updates the view accordingly.

- **Functions:** Receives input from the user, manipulates data in the model, and updates the
view.

- **Example:** A JavaScript function that handles form submissions and updates the data
displayed on the page.

- **How It Works:**

- The user interacts with the view (e.g., by clicking a button).

- The view sends input to the controller.

- The controller processes the input, interacts with the model, and updates the view based on the
changes in the model.

- The model updates the data and notifies the view, which then re-renders to reflect the changes.

b) **Write an AngularJS Program to Demonstrate `ng-init` Directive that Initializes Variable of String,
Number, Array, and Object:**

```html

<!DOCTYPE html>

<html ng-app="myApp">

<head>

<title>ng-init Example</title>

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

<script>
var app = angular.module('myApp', []);

</script>

</head>

<body ng-init="initialize()">

<div ng-controller="myCtrl">

<p>String: {{ stringVar }}</p>

<p>Number: {{ numberVar }}</p>

<p>Array: {{ arrayVar }}</p>

<p>Object: {{ objectVar.name }} - {{ objectVar.age }} years old</p>

</div>

<script>

app.controller('myCtrl', function($scope) {

$scope.initialize = function() {

$scope.stringVar = 'Hello, AngularJS!';

$scope.numberVar = 42;

$scope.arrayVar = ['AngularJS', 'React', 'Vue'];

$scope.objectVar = { name: 'John Doe', age: 30 };

};

});

</script>

</body>

</html>

```

**Explanation:** The `ng-init` directive initializes variables of different types (string, number, array,
and object) when the AngularJS application starts. The `initialize` function sets these variables, and
they are displayed in the view.

c) **Write Advantages and Disadvantages of SPA (Single Page Application):**

- **Advantages:**
1. **Improved User Experience:** SPAs provide a more fluid and interactive user experience by
loading content dynamically without refreshing the entire page.

2. **Faster Navigation:** Since only data and content are updated rather than the entire page,
navigation is quicker and more responsive.

3. **Reduced Server Load:** SPAs often reduce server load because the server provides only data,
while the client handles rendering and logic.

4. **Better Performance:** SPAs can cache resources and data, leading to better performance and
faster load times after the initial page load.

- **Disadvantages:**

1. **Initial Load Time:** The initial load time can be longer because the entire application,
including JavaScript and resources, needs to be loaded upfront.

2. **SEO Challenges:** SPAs can have issues with search engine optimization (SEO) because
content is loaded dynamically, making it harder for search engines to index.

3. **Browser History Management:** Managing browser history and navigation can be complex
since the application uses client-side routing.

4. **JavaScript Dependency:** SPAs rely heavily on JavaScript, which can lead to issues if the
user's browser has JavaScript disabled.

d) **Explain Functions of AngularJS Directive Life Cycle:**

- **Directive Life Cycle Phases:**

1. **Compilation:**

- **Description:** During this phase, AngularJS compiles the template and links it to the
directive’s scope. It processes the template and creates the DOM elements.

- **Function:** Allows the directive to manipulate the DOM and perform actions before the
view is rendered.

2. **Linking:**

- **Description:** This phase is where AngularJS links the compiled DOM elements with the
directive’s scope. It allows directives to bind data and functions to the view.

- **Function:** Directives set up event listeners, bind data, and perform actions after the view is
rendered.

3. **Post-Linking:**
- **Description:** This phase is executed after the linking phase, where additional post-
processing tasks can be performed.

- **Function:** Allows directives to perform cleanup tasks or additional manipulations after the
initial link.

- **Example:**

```javascript

app.directive('myDirective', function() {

return {

restrict: 'E',

template: '<div>{{message}}</div>',

compile: function(element, attrs) {

// Compilation phase

console.log('Compile phase');

return function(scope, element, attrs) {

// Linking phase

console.log('Link phase');

scope.message = 'Hello from Directive!';

};

},

link: function(scope, element, attrs) {

// Post-link phase

console.log('Post-Link phase');

};

});

```

e) **Distinguish Between Factory, Service, and Provider in AngularJS:**

- **Factory:**
- **Definition:** A factory is a function that returns an object or a function. It is used to create
services, and it provides a simple way to configure and initialize the object.

- **Example:**

```javascript

app.factory('myFactory', function() {

var factory = {};

factory.sayHello = function() {

return 'Hello from Factory!';

};

return factory;

});

```

- **Service:**

- **Definition:** A service is a constructor function that is instantiated with the `new` keyword. It
is used to create reusable logic and data across the application.

- **Example:**

```javascript

app.service('myService', function() {

this.sayHello = function() {

return 'Hello from Service!';

};

});

```

- **Provider:**

- **Definition:** A provider is a more configurable way to create services. It has a `$get` method
that returns the service object, and it allows for configuration during the application’s configuration
phase.

- **Example:**

```javascript

app.provider('myProvider', function() {
this.$get = function() {

return {

sayHello: function() {

return 'Hello from Provider!';

};

};

});

```

**Summary:**

- **Factory** returns a value or object and can be used to create services.

- **Service** uses a constructor function and is instantiated with `new`.

- **Provider** is the most configurable option, allowing for configuration and setup before service
instantiation.

Here are the detailed answers for each question:

a) **Model:**

- **Definition:** In the context of AngularJS, the Model represents the data and business logic of
an application. It is responsible for storing and managing the application's data and typically interacts
with external data sources like APIs or databases.

- **Characteristics:**

1. **Data Storage:** Holds the data that the application uses. This can include user data,
application state, or any other information necessary for the application.

2. **Business Logic:** Implements the rules and operations related to the data, such as
calculations, validations, and transformations.

3. **Data Binding:** The model is linked to the view through data binding. Changes in the model
automatically update the view, and user interactions in the view can update the model.

- **Example:**
```javascript

app.controller('myCtrl', function($scope) {

$scope.user = {

name: 'John Doe',

age: 30

};

$scope.updateUser = function(name, age) {

$scope.user.name = name;

$scope.user.age = age;

};

});

```

**Explanation:** In this example, the `user` object represents the model with properties like
`name` and `age`. The `updateUser` function updates these properties, and the changes are reflected
in the view through data binding.

b) **Event Handling:**

- **Definition:** Event handling in AngularJS refers to the process of responding to user


interactions or events within an application, such as clicks, key presses, or mouse movements.

- **Key Concepts:**

1. **Event Directives:** AngularJS provides several directives to handle events, such as `ng-click`,
`ng-change`, `ng-submit`, etc.

2. **Event Binding:** You can bind functions to events using these directives. When the event
occurs, the associated function is executed.

3. **Event Object:** AngularJS provides an event object that can be used to access information
about the event, such as the event type or the target element.

- **Example:**

```html
<!DOCTYPE html>

<html ng-app="myApp">

<head>

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

<script>

var app = angular.module('myApp', []);

app.controller('myCtrl', function($scope) {

$scope.handleClick = function() {

alert('Button clicked!');

};

});

</script>

</head>

<body ng-controller="myCtrl">

<button ng-click="handleClick()">Click Me</button>

</body>

</html>

```

**Explanation:** The `ng-click` directive is used to bind the `handleClick` function to the button's
click event. When the button is clicked, the function displays an alert.

c) **Dependency Injection:**

- **Definition:** Dependency Injection (DI) is a design pattern used in AngularJS to manage


dependencies between components (services, controllers, etc.) by providing them as required rather
than hardcoding them.

- **Key Concepts:**

1. **Inversion of Control:** DI helps in inverting control, where AngularJS injects dependencies


rather than the components creating them. This promotes modularity and testability.
2. **Providers:** Dependencies are defined as providers, which are then injected into
components. AngularJS provides built-in providers such as `$http`, `$scope`, and `$route`.

3. **Configuration:** DI is set up during the application configuration phase, where you can
specify how dependencies should be provided and managed.

- **Example:**

```javascript

app.service('myService', function() {

this.getMessage = function() {

return 'Hello from Service!';

};

});

app.controller('myCtrl', function($scope, myService) {

$scope.message = myService.getMessage();

});

```

**Explanation:** In this example, the `myService` service is injected into the `myCtrl` controller.
The controller uses the service to get a message, demonstrating how dependencies are managed and
provided by AngularJS.

Feel free to ask if you need more details on any of these topics!

You might also like