Angular JS QPS Solutions
Angular JS QPS Solutions
QP1
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.
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.
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.
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.
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.
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.
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.
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.
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>
app.controller('myCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="myCtrl">
<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.
1. **ng-repeat:** Used to iterate over a collection and render a template for each item.
```html
```
```html
<span ng-bind="message"></span>
```
```html
```
1. **Organizational Structure:** Modules help in organizing code into reusable components and
services, making it easier to manage and scale large applications.
```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>
app.controller('myCtrl', function($scope) {
$scope.num1 = 0;
$scope.num2 = 0;
$scope.result = 0;
$scope.multiply = function() {
};
});
</script>
</head>
<body ng-controller="myCtrl">
<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`.
```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>
app.controller('myCtrl', function($scope) {
$scope.changeMessage = function() {
};
});
</script>
</head>
<body ng-controller="myCtrl">
<p>{{message}}</p>
</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.
- **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.
- **$rootScope:**
- **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>
});
});
</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:**
- **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:**
2. **$location:** Provides methods to interact with the browser’s URL, including navigating and
manipulating the URL.
c) **MVC Architecture in Detail:**
- **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
- **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 Controller receives user input from the View and updates the Model.
**Diagram Example:**
```
[View] <-- user input --> [Controller] <-- data manipulation --> [Model]
```
```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>
app.controller('myCtrl', function($scope) {
});
</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.
```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>
app.controller('myCtrl', function($scope) {
});
</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
- **Purpose:** Watches an expression for changes and executes a listener function when the
expression changes.
- **Parameters:**
- `objectEquality` (optional): A boolean that determines whether to check for deep object
equality.
- **Example:**
```javascript
});
```
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() {
});
```
3. **$emit(eventName, [args]):**
- **Parameters:**
- **Example:**
```javascript
```
4. **$broadcast(eventName, [args]):**
- **Parameters:**
- **Example:**
```javascript
```
**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>
app.controller('myCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="myCtrl">
<p>Original: {{text}}</p>
</body>
</html>
```
**Explanation:**
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
$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`.
- **Example:**
```javascript
});
```
- **$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.
- **Example:**
```javascript
app.run(function($rootScope) {
});
```
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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
app.service('primeService', function() {
this.isPrime = function(num) {
return true;
};
});
$scope.number = null;
$scope.checkPrime = function() {
};
});
</script>
</head>
<body ng-controller="myCtrl">
<p>Result: {{result}}</p>
</body>
</html>
```
**Explanation:**
- The `myCtrl` controller uses this service to check if the entered number is prime and displays the
result.
```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 count = 0;
$scope.numbers = [];
$interval(function() {
$scope.numbers.push(count++);
}, 1000);
});
</script>
</head>
<body ng-controller="myCtrl">
<ul>
</body>
</html>
```
**Explanation:**
- The `$interval` service is used to execute a function every 1000 milliseconds (1 second).
- The view updates automatically to display the numbers generated every second.
- **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.
- **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
```
- **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">
</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">
</form>
```
**How It Works:**
- **Model State:** The form and input elements track their own validation state, allowing you to
access these states and display feedback accordingly.
QP2
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.
- **Example:**
```html
```
- **Example:**
```html
```
- **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
<p>Hello, {{name}}!</p>
```
- **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.
- **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.
- **Usage:** It is used to schedule functions to run after a delay and automatically integrates with
AngularJS’s digest cycle.
- **Example:**
```javascript
$timeout(function() {
}, 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.
- **Model:**
- **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) {
});
```
- **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) {
});
```
- 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**.
- **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.
- **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.
- **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>
app.controller('parentCtrl', function($scope) {
});
app.controller('childCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="parentCtrl">
<p>{{parentMessage}}</p>
<div ng-controller="childCtrl">
<p>{{childMessage}}</p>
<p>{{parentMessage}}</p>
</div>
</body>
</html>
```
**Explanation:**
- The child scope inherits from the parent scope, so `childCtrl` can access `parentMessage` in
addition to its own scope data.
```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>
app.service('factorialService', function() {
this.calculate = function(n) {
if (n <= 1) return 1;
};
});
$scope.result = null;
$scope.calculateFactorial = function() {
$scope.result = factorialService.calculate($scope.number);
};
});
</script>
</head>
<body ng-controller="myCtrl">
<p>Factorial: {{result}}</p>
</body>
</html>
```
**Explanation:**
- 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>
$scope.showGames = function() {
$scope.displayList = $scope.games;
};
});
</script>
</head>
<body ng-controller="myCtrl">
<ul>
</ul>
</body>
</html>
```
**Explanation:**
- It assigns the `games` array to `displayList`, which is then displayed in a list using `ng-repeat`.
- **AngularJS:**
- **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
<p>{{message}}</p>
</div>
```
- **JavaScript:**
- **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
```
**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.
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>
</ul>
```
3. **ng-if:**
- **Example:**
```html
```
4. **ng-click:**
- **Purpose:** Binds a click event to a function in the controller, allowing user interactions to
trigger methods.
- **Example:**
```html
```
- **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.
**Example:**
```javascript
app.config(function($provide) {
});
app.run(function($rootScope) {
});
```
```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>
app.controller('myCtrl', function($scope) {
$scope.items = ['Apple', 'Banana', 'Cherry'];
});
</script>
</head>
<body ng-controller="myCtrl">
<ul>
</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>
app.controller('myCtrl', function($scope) {
$scope.students = [
];
});
</script>
</head>
<body ng-controller="myCtrl">
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<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.
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.
- **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.
- **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() {
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() {
});
```
- **Use Case:** When you need to create a singleton service with shared state or behavior.
- **Provider:**
- **Syntax:**
```javascript
app.provider('myProvider', function() {
this.$get = function() {
};
});
```
- **Use Case:** When you need to configure the service during the module's configuration phase
or when the service requires additional setup.
- **ng-submit:**
- **Example:**
```html
<form ng-submit="submitForm()">
<button type="submit">Submit</button>
</form>
```
- **ng-change:**
- **Usage:** Used to perform actions whenever the user modifies the input.
- **Example:**
```html
```
- **ng-focus:**
- **Example:**
```html
```
- **ng-blur:**
- **Usage:** Used to perform actions when the user moves focus away from the input field.
- **Example:**
```html
```
- **$document Service:**
- **Description:** A wrapper around the global `document` object. It provides a way to interact
with the DOM in a platform-independent manner.
- **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) {
});
```
- **$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) {
});
```
- **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.
```javascript
app.filter('reverse', function() {
return function(input) {
if (!input) return;
return input.split('').reverse().join('');
};
});
```
```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>
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>
</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.
- **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.
- **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>
app.controller('myCtrl', function($scope) {
$scope.amount = 1234.56;
});
</script>
</head>
<body ng-controller="myCtrl">
</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.
- **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.
- **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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
$scope.name = 'John';
});
</script>
</head>
<body ng-controller="myCtrl">
<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.
- **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.
- **Use Case:** Suppose you need to validate that a password contains both letters and numbers.
- **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>
app.directive('passwordValidator', function() {
return {
require: 'ngModel',
ngModel.$validators.passwordValidator = function(value) {
};
};
});
app.controller('myCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="myCtrl">
<form name="myForm">
<label for="password">Password:</label>
</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
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.
- **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.
- **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
<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) {
});
```
- **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
$http.get('api/data').then(function(response) {
$scope.data = response.data;
});
});
```
- **Example:**
```html
<p>{{name | uppercase}}</p>
```
- **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.
- **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
$timeout(function() {
$scope.message = "Updated after 2 seconds!";
}, 2000);
});
```
- **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',
ngModel.$validators.passwordValidator = function(value) {
};
};
});
```
**Explanation:** The `passwordValidator` directive checks if a password contains both letters and
numbers.
- **`ng-model`:**
- **Description:** Binds the value of HTML controls (e.g., input, select) to a property on the
scope.
- **Example:**
```html
<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>
</ul>
```
- **`ng-if`:**
- **Example:**
```html
```
- **Description:** Toggles the visibility of HTML elements based on the expression's truthiness.
- **Example:**
```html
```
- **`ng-click`:**
- **Example:**
```html
```
- **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 **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() {
}, 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
```
- **`$log`:**
- **Description:** Provides methods for logging messages to the browser console (e.g., `log`,
`info`, `warn`, `error`).
- **Example:**
```javascript
```
d) **Write an AngularJS Program to Create a Service for Finding the Factorial of a Number:**
```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>
app.service('factorialService', function() {
this.calculate = function(n) {
if (n === 0) return 1;
};
});
app.controller('myCtrl', function($scope, factorialService) {
$scope.factorial = function() {
$scope.result = factorialService.calculate($scope.number);
};
});
</script>
</head>
<body ng-controller="myCtrl">
<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.
```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>
$scope.number = 1234.5678;
});
</script>
</head>
<body ng-controller="myCtrl">
</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.
- **AngularJS:**
- **Features:**
- **Two-Way Data Binding:** Automatically synchronizes data between the model and the view.
- **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.
**Comparison Summary:**
- **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.
- **Definition:** Custom directives in AngularJS allow you to create reusable components and
behavior that can be applied to HTML elements.
- **Ways to Implement:**
```javascript
app.directive('myElement', function() {
return {
restrict: 'E',
};
});
```
**Usage:**
```html
<my-element></my-element>
```
```javascript
app.directive('myAttribute', function() {
return {
restrict: 'A',
element.css('color', 'red');
};
});
```
**Usage:**
```html
```
```javascript
app.directive('myClass', function() {
return {
restrict: 'C',
element.on('click', function() {
alert('Element clicked!');
});
};
});
```
**Usage:**
```html
```
```javascript
app.directive('myComment', function() {
return {
restrict: 'M',
};
});
```
**Usage:**
```html
```
- **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.
```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>
app.controller('myCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="myCtrl">
<ul>
</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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
app.factory('mathService', function() {
return {
add: function(a, b) {
return a + b;
},
subtract: function(a, b) {
return a - b;
};
});
$scope.num1 = 5;
$scope.num2 = 3;
});
</script>
</head>
<body ng-controller="myCtrl">
<p>Sum: {{sum}}</p>
<p>Difference: {{difference}}</p>
</body>
</html>
```
**Explanation:**
- The `myCtrl` controller uses this service to perform calculations and display the results.
- **`$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:**
- **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`.
```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>
app.service('circleService', function() {
this.calculateArea = function(radius) {
};
});
$scope.radius = 5;
$scope.area = circleService.calculateArea($scope.radius);
});
</script>
</head>
<body ng-controller="myCtrl">
</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.
- **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.
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>
app.controller('myCtrl', function($scope) {
$scope.person = {
};
});
</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`.
- **`$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
});
```
- **`$log` Service:**
- **Description:** Provides methods for logging messages to the browser console. It includes
methods like `log`, `info`, `warn`, and `error`.
- **Example Usage:**
```javascript
});
```
- **`$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) {
});
app.controller('myCtrl', function($scope, $rootScope) {
$scope.localValue = $rootScope.globalValue;
});
```
**Summary:**
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.
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
<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:**
- **Simplifies Code:** Makes it easier to maintain and understand the application's data flow.
- **`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
```
- **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.
```javascript
```
- **Explanation:** Creates a new AngularJS module named `myApp`. The empty array `[]`
indicates that there are no dependencies.
```javascript
```
- **Explanation:** Retrieves the existing module `myApp`. This can be used to configure the
module or add components like controllers and services.
- **Benefits:**
QP4
a) **What is AngularJS?**
- **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.
- **Module:**
```javascript
```
- **Controller:**
```javascript
app.controller('myCtrl', function($scope) {
});
```
- **Directive:**
```javascript
app.directive('myDirective', function() {
return {
restrict: 'E',
};
});
```
- **Service:**
```javascript
app.service('myService', function() {
this.sayHello = function() {
return 'Hello!';
};
});
```
- **Filter:**
```javascript
app.filter('customFilter', function() {
return function(input) {
return input.toUpperCase();
};
});
```
- **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.
- **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>
app.controller('myCtrl', function($scope) {
});
</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!".
- **Syntax:**
```javascript
app.controller('controllerName', function($scope) {
$scope.variable = 'value';
});
```
- **Example:**
```javascript
app.controller('myCtrl', function($scope) {
});
```
- **`$scope`:**
- **`scope`:**
- **Definition:** The term `scope` generally refers to any scope object in AngularJS, including
`$scope`, `$rootScope`, and child scopes.
- **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>
app.controller('myCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="myCtrl">
</body>
</html>
```
- **Explanation:** The date filter formats `currentDate` using the `'fullDate'` format, displaying it as
"Saturday, September 2, 2024" (depending on the locale).
- **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
$http.get('https://api.example.com/data')
.then(function(response) {
$scope.data = response.data;
}, function(error) {
console.error(error);
});
});
```
- **Syntax:**
```javascript
app.factory('factoryName', function() {
return {
methodName: function() {
// Logic here
};
});
```
- **Example:**
```javascript
app.factory('mathFactory', function() {
return {
add: function(a, b) {
return a + b;
};
});
});
```
- **Explanation:** The `mathFactory` provides an `add` method for addition. This factory is
injected into the controller to use its functionality.
- **Features:**
- **Direct DOM Manipulation:** Interacts directly with the Document Object Model (DOM) for
updating content on web pages.
- **AngularJS:**
- **Features:**
- **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.
**Summary:**
- **AngularJS** is a framework that builds on JavaScript to provide additional tools and structure
for developing complex applications.
```
- **Advantages of Modules:**
1. **Organization:** Modules help in organizing code into manageable and reusable pieces,
making the application more modular and maintainable.
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.
1. **`ng-submit`:** Triggered when a form is submitted. It can be used to handle form submission
and validation.
```html
<form ng-submit="submitForm()">
<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
```
3. **`ng-focus` and `ng-blur`:** Triggered when an input field gains or loses focus, respectively.
Useful for handling focus-related actions.
```html
```
```html
```
```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>
app.controller('myCtrl', function($scope) {
$scope.num1 = 0;
$scope.num2 = 0;
$scope.result = 0;
$scope.multiply = function() {
};
});
</script>
</head>
<body ng-controller="myCtrl">
<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>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script>
app.service('factorialService', function() {
this.calculateFactorial = function(n) {
if (n === 0) return 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>Factorial: {{factorial}}</p>
</body>
</html>
```
```html
```
- **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
```
- **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.
- **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) {
});
```
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: '='
},
};
});
```
```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) {
});
app.controller('childCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="parentCtrl">
<div ng-controller="childCtrl">
</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.
```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>
app.controller('myCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="myCtrl">
</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.
- **Lower-Case Filter:**
- **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>
app.controller('myCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="myCtrl">
</body>
</html>
```
- **Upper-Case Filter:**
- **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>
app.controller('myCtrl', function($scope) {
});
</script>
</head>
<body ng-controller="myCtrl">
</body>
</html>
```
```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>
app.controller('myCtrl', function($scope) {
$scope.copiedText = '';
$scope.pastedText = '';
$scope.handleCopy = function() {
};
$scope.handlePaste = function() {
};
});
</script>
</head>
<body ng-controller="myCtrl">
</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.
- **Components:**
1. **Model:**
- **Definition:** Represents the data and business logic of the application. It is responsible for
retrieving, processing, and storing data.
- **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.
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 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">
</div>
<script>
app.controller('myCtrl', function($scope) {
$scope.initialize = function() {
$scope.numberVar = 42;
};
});
</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.
- **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.
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>',
// Compilation phase
console.log('Compile phase');
// Linking phase
console.log('Link phase');
};
},
// Post-link phase
console.log('Post-Link phase');
};
});
```
- **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() {
factory.sayHello = function() {
};
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() {
};
});
```
- **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() {
};
};
});
```
**Summary:**
- **Provider** is the most configurable option, allowing for configuration and setup before service
instantiation.
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 = {
age: 30
};
$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:**
- **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>
app.controller('myCtrl', function($scope) {
$scope.handleClick = function() {
alert('Button clicked!');
};
});
</script>
</head>
<body ng-controller="myCtrl">
</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:**
- **Key Concepts:**
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() {
};
});
$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!