0% found this document useful (0 votes)
115 views15 pages

Question Bank-1

The document discusses controllers in AngularJS and provides examples. It states that controllers should not be used for directly manipulating the DOM, formatting input, filtering output, or managing other component lifecycles. Controllers are intended for business logic only. An example is given showing a controller used with $scope to display a concatenated first and last name. The document also discusses AngularJS services, watches, and the digest cycle for updating views.

Uploaded by

snehadrdn
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)
115 views15 pages

Question Bank-1

The document discusses controllers in AngularJS and provides examples. It states that controllers should not be used for directly manipulating the DOM, formatting input, filtering output, or managing other component lifecycles. Controllers are intended for business logic only. An example is given showing a controller used with $scope to display a concatenated first and last name. The document also discusses AngularJS services, watches, and the digest cycle for updating views.

Uploaded by

snehadrdn
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/ 15

1. a) Describe the scenarios where Controllers cannot be used in AngularJS.

The following scenarios where Controllers cannot be used in AngluarJS

 Manipulate DOM — Controllers should contain only business logic. Putting any
presentation logic into Controllers significantly affects its testability. AngularJS
has data binding for most cases and directives to encapsulate manual DOM
manipulation.
 Format input — Use AngularJS form controls instead.
 Filter output — Use AngularJS Built-in filters instead.
 Share code or state across controllers — Use AngularJS services instead.
 Manage the life-cycle of other components (for example, to create service
instances).

b) Develop an AngularJS code snippet using Controllers and $scope to create a simple
web page to display the concatenation of the First name and Second name as input of a
user.

<!DOCTYPE html>
<html>
<head>
<title>ng-controller Directive</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName = " ";
$scope.lastName = " ";
});
</script>
</head>
<body>
<center>
<h1 style="color:green">GeeksforGeeks</h1>
<h2>ng-controller Directive</h2>
<div ng-app="myApp" ng-controller="myCtrl">
First Name:
<input type="text" ng-model="firstName">
<br> Last Name:
<input type="text" ng-model="lastName">
<br><br>
Full Name: {{firstName + lastName}}
</div>
</center>
</body>
</html>
Output:

2. a) Describe the function responsible for invoking the notification process of the framework
in AngularJS.

During the framework initialization, the compiler walks through the DOM tree
looking for directives. When it finds the ngModel directive attached to any kind of
input field, it binds its own scope's $apply function to the onkeydown event. This
function is responsible for invoking the notification process of the framework called
the digest cycle. The terms related to Digest cycle are AngularJs watch, watch counts, and
watch list.
AngularJs watch: It is provided by AngularJs Framework to keep track of scope variables
and the change in their values.
Watch counts: Angular performs watching on data-binded variables but if we want we can
perform watch on normal variables as well, using watch function. It takes parameter the
variable that we explicitly want to watch.
Watch list: Maintains a list of all the watches associated with an angular application. i.e all
the data bindings being monitored.

b) Develop an AngularJS using custom filters to create a simple web page with a search box
that, when used, displays a list of items that have been pre-specified in the code.
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>AngularJS Filters Example</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js">
</script>
</head>
<body>
<div ng-controller="myController">
<input type="text" ng-model="searchText" placeholder="Search">
<ul>
<li ng-repeat="item in items | filter: searchText">{{ item.name }}</li>
</ul>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.items = [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' },
{ name: 'Another Item' },
// ... more items
];
});
</script>
</body>
</html>

Output:

3. a) How can you create a custom directive in AngularJS that, when utilized, outputs
information about a student, such as their name and roll number in the below format

Student : ABC, Roll No: 1

Student : XYZ, Roll No: 2

Specify the steps involved in implementing and using custom directives for this specific
purpose.

<html>
<head>
<title>Angular JS Custom Directives</title>
</head>
<body>
<h2>AngularJS Sample Application</h2>

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


<student name = "Mahesh"></student><br/>
<student name = "Piyush"></student>
</div>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.directive('student', function() {
var directive = {};
directive.restrict = 'E';
directive.template = "Student: <b>{{student.name}}</b> ,
Roll No: <b>{{student.rollno}}</b>";
directive.scope = {
student : "=name"
}
directive.compile = function(element, attributes) {
element.css("border", "1px solid #cccccc");

var linkFunction = function($scope, element, attributes) {


element.html("Student: <b>"+$scope.student.name +"</b> ,
Roll No: <b>"+$scope.student.rollno+"</b><br/>");
element.css("background-color", "#ff00ff");
}
return linkFunction;
}
return directive;
});
mainApp.controller('StudentController', function($scope) {
$scope.Mahesh = {};
$scope.Mahesh.name = "Mahesh Parashar";
$scope.Mahesh.rollno = 1;

$scope.Piyush = {};
$scope.Piyush.name = "Piyush Parashar";
$scope.Piyush.rollno = 2;
});
</script>
</body> </html>

Output:

4 a) How can you demonstrate the implementation of an Ajax service in AngularJS to set the
response for students with the highest priority in a student record? Provide a step-by-step
illustration of the code or configuration required to achieve this functionality.
We have the file data.txt, which will include the records of the student. An Ajax call will be
made by the $http service. It is going to divert & set the response to the students having
priority. After this extraction, the tables will be drawn up in the HTML, which will be based
on the students model.

. The data.txt file:


[
{
"Name" : "Ronaldo",
"Goals" : 128,
"Ratio" : "69%"
},
{
"Name" : "James",
"Goals" : 007,
"Ratio" : "70%"
},
{
"Name" : "Ali",
"Goals" : 786,
"Ratio" : "99%"
},
{
"Name" : "Lionel ",
"Goals" : 210,
"Ratio" : "100%"
}
]

.Code
<!DOCTYPE html>
<html>
<head>
<title>AngularJS AJAX - $http</title>
<style>
table, th, td {
border: 1px #2E0854;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #F6ADCD;
}
table tr:nth-child(even) {
background-color: #42C0FB;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">
</script>
</head>
<body>
<center>
<h1 style="color:green">GeeksforGeeks</h1>
<h3>AJAX - $http</h>
<div ng-app="" ng-controller="studentController">
<table>
<tr>
<th>Name</th>
<th>Goals</th>
<th>Ratio</th>
</tr>
<tr ng-repeat="student in students">
<td>{{ Player.Name }}</td>
<td>{{ Player.Goals}}</td>
<td>{{ Player.Ratio}}</td>
</tr>
</table>
</div>
<script>
function studentController($scope, $http) {
var url = "/data.txt";

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

5. a) How is error handling accomplished using Promises in AngularJS? Provide an


explanation of the methods employed to effectively handle errors within Promise-based
operations in AngularJS applications.

 Error handling with an Angular promise involves using the .catch() method to
handle errors occurring during asynchronous operations.
 When working with promises, you can attach an error handler using
the .catch() method.
 This allows you to centralise the error-handling logic instead of scattering it across
multiple callbacks.
 If an error occurs during the execution of a promise chain, the control jumps to
the nearest .catch() callback, where you can handle the error appropriately.

Here’s an example demonstrating error handling with promises in AngularJS:

$http.get('https://api.example.com/data')
.then(function(response) {
var processedData = response.data;
return processedData;
})
.catch(function(error) {
console.log('Error:', error);
});

b) Explore the various techniques employed within the AngularJS $http service for initiating
a request to the server and receiving a response. Provide insights into the methods and
functionalities utilized during this process in AngularJS.

The AngularJS $http service makes a request to the server, and returns a response.
 $http.get
 $http.post
 $http.head
 $http.put
 $http.delete
 $http.patch

$http.get: The .get method is a shortcut method of the $http service


get(url, [config]);
Parameters

Param Type Details

stringTrustedObject Absolute or relative URL of the resource that is being requested;


url
or an object
created by a call to $sce.trustAsResourceUrl(url).

config Object Optional configuration object. See $http() arguments.


(optional
)
Returns

HttpPromise A Promise that will be resolved or rejected with a response object.


See $http() return value.

$thhp.post: post(url, data, [config]); Shortcut method to perform POST request.

Parameters

Param Type Details

string Relative or absolute URL specifying the destination of the request


url

data * Request content

config Object Optional configuration object. See $http() arguments.


(optional)

Returns

HttpPromise A Promise that will be resolved or rejected with a response object.


See $http() return value.

$http.head : head(url, [config]); Shortcut method to perform HEAD request.

Parameters

Param Type Details

stringTrustedObject Absolute or relative URL of the resource that is being


url
requested; or an object created by a call
to $sce.trustAsResourceUrl(url).

config Object Optional configuration object. See $http() arguments.


(optional
)
Returns

HttpPromise A Promise that will be resolved or rejected with a response object.


See $http() return value.

$http.put: put(url, data, [config]); Shortcut method to perform PUT request.

Parameters

Param Type Details

string Relative or absolute URL specifying the destination of the request


url

data * Request content

config Object Optional configuration object. See $http() arguments.


(optional)

Returns

HttpPromise A Promise that will be resolved or rejected with a response object.


See $http() return value.

$http.delete:
delete(url, [config]); Shortcut method to perform DELETE request.

Parameters

Param Type Details

string Absolute or relative URL of the resource that is being requested; or


url
TrustedObject an object created by a call to $sce.trustAsResourceUrl(url).

config Object Optional configuration object. See $http() arguments.


(optional)
Returns

HttpPromise A Promise that will be resolved or rejected with a response


object. See $http() return value.

$http.patch: patch(url, data, [config]); Shortcut method to perform PATCH request.

Parameters

Param Type Details

string Relative or absolute URL specifying the destination of the request


url

data * Request content

config Object Optional configuration object. See $http() arguments.


(optional)

Returns

HttpPromise A Promise that will be resolved or rejected with a response object.


See $http() return value.

6 a) How is data retrieval from remote servers accomplished in AngularJS? Provide an


overview of the mechanisms and techniques employed in AngularJS to read data from remote
servers

The $http service, which serves the task for reading all the data that is available on the
remote servers. $http.json is one of the method used to serve this purpose.

$http.json: jsonp(url, [config]); Shortcut method to perform JSONP request.


 JSONP requests must specify a callback to be used in the response from the server.
This callback is passed as a query parameter in the request.

$http.jsonp('some/trusted/url', {jsonpCallbackParam: 'callback'})

 We can also specify a default callback parameter name


in $http.defaults.jsonpCallbackParam. Initially this is set to 'callback'.
Parameters

Param Type Details

stringTrustedObject Absolute or relative URL of the resource that is being


url
requested; or an object created by a call
to $sce.trustAsResourceUrl(url).

config Object Optional configuration object. See $http() arguments.


(optional
)

Returns

HttpPromise A Promise that will be resolved or rejected with a response object.


See $http() return value.

b) Examine the approaches employed within the AngularJS $q service for executing
functions asynchronously and effectively, utilizing their return values.

$q is a built-in service which helps in executing asynchronous functions, and use their return
values (or exception) when they are finished with processing.
The below methods are employed for asynchronous execution of the functions.
Methods

 resolve(value) – resolves the derived promise with the value. If the value is a
rejection constructed via $q.reject, the promise will be rejected instead.
Use $q.when() or $q.resolve() when you want to immediately resolve a
promise from a non-promise Object.

 reject(reason) – Using this, it will immediately reject a promise and this comes in
handy for things such as HTTP Interceptors at the point of no return to return, so
we can just return a rejected promise Object. Resolving with a rejection
constructed via $q.reject.
 notify(value) - provides updates on the status of the promise's execution. This may
be called multiple times before the promise is either resolved or rejected.

7. Create an AngularJS webpage that utilizes built-in services to perform addition of two
numbers.

<!DOCTYPE html>

<html ng-app="additionApp">

<head>
<title>AngularJS Addition</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular.min.js"></
script>
</head>
<body ng-controller="additionController">

<h2>AngularJS Addition</h2>

<input type="number" ng-model="number1" placeholder="Enter number 1">


<input type="number" ng-model="number2" placeholder="Enter number 2">
<button ng-click="addNumbers()">Add</button>

<p ng-if="result">Result: {{ result }}</p>

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

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


$scope.number1 = 0;
$scope.number2 = 0;
$scope.result = 0;

$scope.addNumbers = function () {
$scope.result = $scope.number1 + $scope.number2;
};
});
</script>
</body>
</html>

8. Create an AngularJS webpage that uses Dependency Injecting services like Factory, Value
and Service to perform the Square of a number.

<html>
<head>
<title>Angular JS Services</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>

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


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

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

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

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

OUTPUT:

You might also like