Anjular JS 2

It has been developed by one of the biggest technology giants Google. It is a JavaScript framework that helps you to create dynamic Web applications.

It supports to use HTML as the template language and enables the developer to create extended HTML tags that help to represent the application’s components clearly. These tags make the code efficient by reducing the lines of code that a developer may need to write when using JavaScript.

It is open-source and is licensed under the Apache License version 2.0.

It helps to develop an easy to maintain architecture that can be tested at client side code. 

 Q-7. What Are The Security Features Provided By AngularJS?

AngularJS provides built-in protection from the following security flaws.

It prevents cross-side scripting attacks: Cross-site scripting is a technique where anyone can send a request from client side and can get the confidential information easily.

It prevents HTML injection attacks.

It prevents XSRF protection for server side communication: It can be handled by “Auth token” mechanism. When the user logins for the first time a user id and password is sent to the server and it will, in turn, return an auth token. Now, this token does the authentication in the future transactions.

 Q-8. What Are The Web Application Security Risks That A Web Developer Should Avoid While Doing Development Using AngularJS?

Following are the most critical web application development flaws that a developer should take care of:

Injection attack.

Broken Authentication and Session Management.

Cross-Site Scripting (XSS)

Insecure direct object references.

Security misconfiguration.

Sensitive Data Exposure.

Missing Functions Level Access Control.

Cross Site Request Forgery (CSRF).

Using components that possess vulnerabilities.

In-validated redirects and forwards. 

Q-9. Explain What Are Directives? Mention Some Of The Most Commonly Used Directives In AngularJS Application?

AngularJS extends the behavior of HTML and DOM elements with new attributes called Directives. It directs the AngularJS’s HTML compiler ($compile) to attach a special behavior to that DOM element. This AngularJS component starts with prefix “ng”.

Following is the list of AngularJS built-in directives.

ng-bind – The ng-bind directive tells AngularJS to replace the content of an HTML element with the value of a given variable, or expression.

If there is any change in the value of the given variable or expression, then the content of the specified HTML element will also be updated accordingly. It supports one-way binding only.

ng-model – This directive is used to bind the value of HTML controls (input, select, text area) to application data. It is responsible for binding the view into the model, which other directives such as input, text area, and select require. It supports two-way data binding.

ng-class – This directive dynamically binds one or more CSS classes to an HTML element. The value of the ng-class directive can be a string, an object, or an array.

ng-app – Just like the “Main()” function of Java language, this directive marks the beginning of the application to AngularJS’s HTML compiler ($compile). If we do not use this directive first, an error gets generated.

ng-init – This is used to initialize the application data so that we can use it in the block where it is declared. If an application requires local data like a single value or an array of values, this can be achieved using the ng-init directive.

ng-repeat – This repeats a set of HTML statements for defined number of times. The set of HTML statements will be repeated once per item in a collection. This collection must be an array or an object.

We can even create our own directives too and use them in our AngularJS Application. 

Q-10. What Are Expressions In AngularJS?

AngularJS binds data to HTML using Expressions. It can be written inside double braces: {{ expression}} or inside a directive as ng-bind=”expression”. AngularJS solves the expression and returns the result exactly where that expression is written.

AngularJS expressions are much like JavaScript expressions: it can contain literals, operators, and variables.

For example –

JavaScript

1

2

3

4

{{ 2 + 2 }} (numbers)

{{Name + " " + email}} (string)

{{ Country.Name }} (object)

{{ fact[4] }} (array)

 Q-11. What Are Filters? Explain Different Filters Provided By AngularJS?

An AngularJS Filter changes or transforms the data before passing it to the view. These Filters work in combination with AngularJS expressions or directives. AngularJS uses pipe character (“|”) to add filters to the expressions or directives. For example:

AngularJS provides following filters to transform data.

currency – It is used to format a number to a currency format.

date – It is required to format a date to a specified format.

filter – It chooses a subset of items from an array.

json – It formats an object to a JSON string.

limitTo – Its purpose is to create an array or string containing a specified number of elements/characters. The elements are selected, either from the beginning or the end of the source array or string. This depends on the value and sign (positive or negative) of the limit.

lowercase – This filter converts a string to lower case.

number – It formats a number as a text.

orderBy – It enables to sort an array. By default, sorting of strings happens alphabetically. And sorting of numbers is done numerically. It also supports a comparator function where we can define what will be counted as a match or not.

uppercase – This filter converts a string to upper case. 

Q-12. What Are Angular Prefixes $ And $$?

To prevent accidental name collisions within the code, AngularJS prefixes the names of public objects with $ and the names of private objects with $$.

It is recommended that $ or $$ prefix should not be used in the code otherwise. 

Q-15. What Is $Scope In AngularJS?

It is an application object. And behaves as the owner of the apps variables and functions. Scope object has access to both View and controller. Thus it works as a medium of communication between both of them. This object contains both data and functions. We can use it to access model data of the controller.

Following are the key characteristics of the scope object.

It provides observers to watch for all the model changes.

Provides the ability to propagate model changes through the application as well as outside the system to other associated components.

Scopes can be nested in such a way that they can isolate functionality and model properties.

Provides an execution environment in which expressions are evaluated. 

Q-16. What Is “$RootScope” In AngularJS?

Every AngularJS application has a “$rootScope” that is the top most scope created on the DOM element. An app can have only one $rootScope which will be shared among all its components. It contains the ng-app directive. Every other scope is its child scope. It can watch expressions and propagate events. Using root scope we can set the value in one controller and read it from the other controller. 

Q-18. What Is SPA (Single Page Application) In AngularJS?

Single-Page Applications (SPAs) are web applications that fit on a single HTML page. It dynamically updates the web page as the user performs actions on the app.

SPAs use AJAX and HTML to create quick and responsive web apps. A single page load extracts all the web app code (JS, HTML, CSS).

Thus the user navigates to different parts of the application quickly as it happens without refreshing the whole page.

Key Characteristics of Single-Page Applications are as follows.

Its UI is fast and responsive. Also, the Back/Forward buttons present in the UI work properly.

IT contains more JavaScript code than actual HTML as compared to other applications.

Dynamic data loading occurs from the server-side. The API uses restful web service with JSON format.

It allows to pre-load and cache all the app pages. Thus fewer data download requests are made towards the server.

Applications written in AngularJS are cross-browser compliant. It automatically handles the JavaScript code suitable for each browser.

Even if the user has lost the internet connection, then also the SPA can work. As all the pages load in the starting itself. 

Q-19. What Is The Difference Between $Scope And Scope?

It is mandatory to use <$scope> while defining a controller. However, the “scope” will be used to create a link function for the custom directive. Both of them refer to “scope” object in AngularJS. The difference between them is that <$scope> uses dependency injection whereas “scope” does not.

Factory methods like controller, filter, service etc receive its arguments via dependency injection (DI). In DI, the order of passing the arguments does not matter. For example, a controller may be defined as (let’s define $scope as the first parameter in this case):

JavaScript

1

2

myApp.controller(‘MyController’, [‘$scope’, function($scope, $http) {

//rest of the code goes here }

OR ( if $scope is the second parameter)

JavaScript

1

2

myApp.controller(‘MyController’, [‘$scope’, function($http, $scope) {

//rest of the code goes here }

Thus, AngularJS does not care for the position of “$scope” in both the cases. It uses the argument name to retrieve an object out of the dependency injection container. 

But, in the case of directive linker function, the position of scope matters, as it does not use DI. The reason being that the supplied arguments are received by its caller. In this case, the very first parameter has to be the scope as per AngularJS syntax.

JavaScript

1

2

3

4

5

6

7

8

app.directive(“myDirective”, function() {

  return {

         scope: {};

         link: function(scope, element, attrs) {

        // code goes here.

                                                                          }

                };

              });

In the case of non-dependency injected arguments, we can also give a name to injected objects. The above code can be re-written as:

JavaScript

1

2

3

4

5

6

7

8

app.directive(“myDirective”, function() {

  return {

         scope: {};

         link: function(foo, bar, biz) {

        // code goes here.

                                                                          }

                };

              });

To summarize, in DI case, we pass the <scope object> as <$scope> whereas, in non-DI cases, the <scope object> is returned either as a scope or with any name.

 Q-20. How Is AngularJS Compiled?

Angular’s HTML compiler allows you to teach the browser, new HTML syntax. It allows the developer to attach new behaviors or attributes to any HTML element called as directives. AngularJS compilation process takes place in the web browser itself. It does not involve any server-side or pre-compilation step.

AngularJS uses <$compiler> service to compile the angular HTML page. Its compilation begins after the HTML page (static DOM) is fully loaded.

It occurs in two phases.

Compile – It looks into the entire DOM and collects all of the directives. The result is a linking function.

Link – It combines the directives with a scope and produces a live view. Any changes in the <scope model> get reflected in the view, and any operations done by the user in the view gets reflected in the <scope model>.

The concept of compile and link has come from C language. Here the code is compiled first and then linked. 

Q-21. How Is AngularJS Compilation Different From Other JavaScript Frameworks?

Javascript frameworks like backbone and jQuery process the template as a string and returns the result as a string. You have to dump this resulting string into the DOM where you wanted it with innerHTML().

AngularJS process the template in another way. It directly works on HTML DOM rather than strings and manipulates it as required. It uses two-way data binding between model and view to sync the data. 

Q-24. What Is $RouteProvider In AngularJS?

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

Let’s see the following example:

JavaScript

1

2

3

4

5

6

7

8

9

10

var mainApp = angular.module("mainApp", ['ngRoute']);

mainApp.config(['$routeProvider', function($routeProvider) {

   $routeProvider.

   when('/addEmployee', {

      templateUrl: 'addEmployee.htm', controller: 'AddEmployeeController'

   }).

 otherwise({

      redirectTo: '/addEmployee'

   });

}]);

Following are the important points to be considered in above example.

routeProvider is defined as a function under config of the mainApp module using a key as ‘$routeProvider’.

$routeProvider.when defines a URL “/addEmployee” which is then mapped to “addEmployee.htm”. This <addEmployee.htm> should be present in the same path as main HTML page.

“otherwise” is used to set the default view.

“controller” is used to set the corresponding controller for the view. 

Q-26. What Directives Are Used To Show And Hide HTML Elements In AngularJS?.

The directives used to show and hide HTML elements in the AngularJS are <ng-show> and <ng-hide>. They do this based on the result of an expression.

Its syntax is as follows.

JavaScript

1

<element ng-show="expression"></element>

When the expression for <ng-show> evaluates to true, then HTML element(s) are shown on the page, otherwise the HTML element is hidden. Similarly, <ng-hide> directive hides the HTML element if the expression evaluates to true.

Let’s take the following example.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

<div ng-controller="MyCtrl">

        <div ng-show="data.isShow">ng-show Visible</div>

        <div  ng-hide="data.isHide">ng-hide Invisible</div>

</div>

<script>

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

       app.controller("MyCtrl", function ($scope) {

              $scope.data = {};

              $scope.data.isShow = true;

              $scope.data.isHide =  true;

        });

</script>

 Q-27. Explain The Directives Ng-If, Ng-Switch, And Ng-Repeat?.

A) <Ng-If>.

This directive can add/remove HTML elements from the DOM based on an expression. If the expression is true, it adds a copy of HTML elements to the DOM. If the expression evaluates to false, this directive removes the HTML element from the DOM.

JavaScript

1

2

3

4

5

6

7

8

9

10

<div ng-controller="MyCtrl">

        <div ng-if="data.isVisible">ng-if  Visible</div>

</div>

<script>

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

       app.controller("MyCtrl", function ($scope) {

              $scope.data = {};

              $scope.data.isVisible = true;

        });

</script>

 B) <Ng-Switch>.

This directive can add/remove HTML elements from the DOM conditionally based on scope expression.

Child elements with the <ng-switch-when> directive will be displayed if it gets a match, else the element and its children get removed. It also allows defining a default section, by using the <ng-switch-default> directive. It displays a section if none of the other sections match.

Let’s see the following example that displays the syntax for <ng-switch>.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<div ng-controller="MyCtrl">

        <div ng-switch on="data.case">

                <div ng-switch-when="1">Shown when case is 1</div>

                <div ng-switch-when="2">Shown when case is 2</div>

                <div ng-switch-default>Shown when case is anything else than 1 and 2</div>

         </div>

</div>

<script>

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

       app.controller("MyCtrl", function ($scope) {

              $scope.data = {};

              $scope.data.case = true;

       });

</script>

 C) <Ng-Repeat>.

This directive is used to iterate over a collection of items and generate HTML from it.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

<div ng-controller="MyCtrl">

       <ul>

             <li ng-repeat="name in names">

                  {{ name }}

             </li>

       </ul>

</div>

<script>

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

app.controller("MyCtrl", function ($scope) {

        $scope.names = [ 'Mahesh', 'Raj', 'Diksha' ];

});

</script>

 Q-29. What Is A Factory Method In AngularJS?.

A factory is a simple function which allows you to add some logic before creating the object. In the end, it returns the created object.

Syntax.

JavaScript

1

app.factory('serviceName',function(){ return serviceObj;})

Creating Service Using The Factory Method.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

 <script>

//creating module

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

 

 //define a factory using factory() function

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

  var serviceObj = {};

 serviceObj.function1 = function () {

 //TO DO:

 };

 

 serviceObj.function2 = function () {

 //TO DO:

 };

 return serviceObj;

});

 </script>

When To Use Factory?

It is just a collection of functions, like a class. Hence, it can be instantiated in different controllers when you are using it with a constructor function. 

 Q-37. What Is A Controller In AngularJS?

Answer.

A Controller is a set of JavaScript functions which is bound to a specified scope, the ng-controller directive. Angular creates a new instance of the Controller object to inject the new scope as a dependency. The role of the Controller is to expose data to our view via $scope and add functions to it, which contains business logic to enhance view behavior.

Controller Rules.

A Controller helps in setting up the initial state of the scope object and define its behavior.

The Controller should not be used to manipulate the DOM as it contains only business logic. Rather, for manipulating the DOM, we should use data binding and directives.

Do not use Controllers to format input. Rather, using angular form controls is recommended for that.

Controllers should not be used to share code or states. Instead, use angular services for it.

Steps For Creating A Controller.

It needs ng-controller directive.

Next step is to add Controller code to a module.

Name your Controller based on functionality. Its name should follow camel case format (i.e. SampleController).

Set up the initial state of the scope object.

Declaring a Controller using ng-Controller directive.

JavaScript

1

2

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

</div>

Following code displays the definition of SampleController.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<script>

   function SampleController($scope) {

      $scope.sample = {

         firstSample: "INITIAL",

         lastSample: "Initial",

         

         fullName: function() {

            var sampleObject;

            sampleObject = $scope.sample;

            return sampleObject.firstSample + " " + sampleObject.lastSample;

         }

      };

   }

</script>

 Q-38. What Does A Service Mean In AngularJS? Explain Its Built-In Services?

Answer.

Services are functions that are bound to perform specific tasks in an application.

It gives us a method, that helps in maintaining the angular app data for its lifetime.

It gives us methods, that facilitate to transfer data across the controllers in a consistent way.

It is a singleton object and its instance is created only once per application.

It is used to organize and share, data and function across the application.

Two main execution characteristics of angular services are that they are Singleton and lazy instantiated.

1. Lazily instantiated –

It means that AngularJS instantiates a service only when a component of an application needs it. This is done by using dependency injection method, that makes the Angular codes, robust and less error prone.

2. Singletons –

Each application component dependent on the service, work with the single instance of the service created by the AngularJS.

Let us take an example of a very simple service that calculates the square of a given number:

JavaScript

1

2

3

4

var CalculationService = angular.module('CalculationService', [])

.service('Calculation', function () {

    this.square = function (a) { return a*a};

});

AngularJS Internal Services –

AngularJS provides many built-in services. Each of them is responsible for a specific task. Built-in services are always prefixed with the $ symbol.

Some of the commonly used services in any AngularJS application are as follows:

$http – used to make an Ajax call to get the server data.

$window – Provides a reference to a DOM object.

$Location – Provides reference to the browser location.

$timeout – Provides a reference to window.set timeout function.

$Log – used for logging.

$sanitize – Used to avoid script injections and display raw HTML in the page.

$Rootscope – Used for scope hierarchy manipulation.

$Route – Used to display browser based path in browser URL.

$Filter – Used for providing filter access.

$resource – Used to work with Restful API.

$document – Used to access the window. Document object.

$exceptionHandler – Used for handling exceptions.

$q – Provides a promise object.

$cookies – This service is useful to write, read and delete browser cookies.

$parse – This service is useful to convert AngularJS expression into a function.

$cacheFactory – This service evaluates the specified expression when the user changes the input.

 Q-39. What Are Different Ways To Create Service In AngularJS?

Answer.

There are 5 different ways to create services in AngularJS.

Value

Factory

Service

Provider

Constant

Let’s discuss, each of the above AngularJS service types one by one with code example:

1. AngularJS Value.

It is the simplest service type supported by AngularJS that we can create and use. It is similar to a key-value pair or like a variable having a value. It can store only a single value. Let’s take an example and create a service that displays username:

JavaScript

1

2

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

app.value("username","Madhav");

Code to use “Value”:

We can use this service anywhere by using dependency injection. Following example injects the service in a controller:

JavaScript

1

2

3

app.controller("MainController",function($scope, username){

$scope.username=username;

});

In the above example, we have created a Value service “username” and used it in MainController.

2. AngularJS Factory.

Value service may be very easy to write but, it lacks many important features. So, the next service type we will look at is “Factory” service. After its creation, we can even inject other services into it. Unlike Value service, we cannot add any dependency in it.

Let’s take an example to create a Factory service.

JavaScript

1

2

3

4

5

6

app.factory("username",function(){

var name="John";

return {

name:name

}

});

The above code shows that Factory service takes “function” as an argument. We can inject any number of dependencies or methods in this “function” as required by this service. This function must return some object. In our example, it returns an object with the property name. Now, let us look, as to how we can use this service:

Code to use “Factory”:

The function returns an object from service which has a property name so we can access it and use it anywhere. Let’s see how we can use it in the controller:

JavaScript

1

2

3

app.controller("MainController",function($scope, username){

$scope.username=username.name;

});

We are assigning the username from factory service to our scope username.

3. AngularJS Service.

It works same as the “Factory” service. But, instead of a function, it receives a Javascript class or a constructor function as an argument. Let’s take an example. Suppose we have a function:

JavaScript

1

2

3

function MyExample(num){

this.variable="value";

}

Now, we want to convert the function into a service. Let’s take a look at how we can do this with “Factory” method:

JavaScript

1

2

3

app.factory("MyExampleService",["num" ,function(num){

return new MyExample(num);

}]);

Thus in this way, we will create its new instance and return it. Also, we have injected <num> as a dependency in Factory service. Now, let’s see how we can do this using Service type:

JavaScript

1

app.service("MyExampleService",["num", MyExample]);

Thus, we have called the service method on the module and provided its name, dependency, and the name of the function in an array.

4. AngularJS Provider.

It is the parent of all the service types supported by AngularJS, except the “Constant” that we will discuss in the next section. It is the core of all the service types. Thus we can say that other services work on top of it. It allows us to create a configurable service that must implement the <$get> method.

We use this service to expose the API that is responsible for doing the application-wide configuration. The configuration should complete before starting the application.

Let’s take an example.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

app.provider('authentication', function() {

   var username = "John";

   return {

       set: function(newUserName) {

           username = newUserName;

       },

       $get: function() {

           function getUserName() {

               return username;

           }

           return {

               getUserName: getUserName

           };

       }

   };

});

This example initializes a provider with its name as “authentication”. It also implements a <$get> function, which returns a method “getUsername” which in turn returns the private variable called username. This also has a setter, using it we can set the username on application startup as follows:

JavaScript

1

2

3

app.config(["authenticationProvider", function(authenticationProvider) {

   authenticationProvider.set("Mihir");

}]);

5. AngularJS Constant.

As the name suggests, this service helps us to declare constants in our application. We can then use them wherever needed, just by adding it as a dependency. There are many places, where we use constants like some base URLs, application name, etc.

We just define them once and use them anywhere as per our need. Thus, this technique allows us to write the definition at one place. If there is any change in the value later, we have to do the modifications at one place only.

Here is an example of how we can create constants:

JavaScript

1

app.constant('applicationName', 'Service Tutorials');

 Q-40. What Is The Difference Between The $Watch, $Digest, And $Apply?.

In AngularJS $scope object is having different functions like $watch(), $digest() and $apply() and we will call these functions as central functions. The AngularJS central functions $watch(), $digest(), and $apply() are used to bind data to variables in view and observe changes happening in variables.

A) $Watch() –

The use of this function is to observe changes in a variable on the $scope. It triggers a function call when the value of that variable changes. It accepts three parameters: expression, listener, and equality object. Here, listener and equality objects are optional parameters.

JavaScript

1

$watch(watchExpression, listener, [objectEquality]).

Following is the example of using $watch() function in AngularJS applications.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

<html> 

<head> 

    <title>AngularJS Watch</title>

    <script src="lib/angular.js"></script> 

    <script> 

         var myapp = angular.module("myapp", []); 

         var myController = myapp.controller("myController", function      

              ($scope) { 

               $scope.name = 'dotnet-tricks.com'; 

               $scope.counter = 0; 

              //watching change in name value 

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

                  $scope.counter = $scope.counter + 1; 

                       }); 

}); 

</script> 

</head>

 <body ng-app="myapp" ng-controller="myController"> 

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

<br /><br /> 

Counter: {{counter}} 

</body> 

</html>

B) $Digest() –

This function iterates through all the watch list items in the $scope object, and its child objects (if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed or not. If the value has changed, AngularJS calls the listener with the new value and the old value.

The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case, you have to call it yourself.

Following is the example of using $digest() function in AngularJS applications:

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<html> 

<head> 

 <title>AngularJS Digest Example</title>

<script src="lib/jquery-1.11.1.js"></script> 

<script src="lib/angular.js"></script> 

</head> 

<body ng-app="app"> 

     <div ng-controller="Ctrl"> 

             <button class="digest">Digest my scope!</button>

                 <br /> 

                 <h2>obj value : {{obj.value}}</h2> 

    </div> 

 <script> 

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

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

            $scope.obj = { value: 1 }; 

           $('.digest').click(function () { 

                 console.log("digest clicked!"); 

                 console.log($scope.obj.value++); 

                 //update value 

                $scope.$digest();

}); 

}); 

</script> 

</body> 

</html> 

C) $Apply() –

AngularJS automatically updates the model changes which are inside AngularJS context. When you apply changes to any model, that lies outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform the Angular about the changes by calling $apply() manually. When the $apply() function call finishes, AngularJS calls $digest() internally, to update all data bindings.

Following are the key differences between $apply() and $digest().

Its use is to update the model properties forcibly.

The $digest() method evaluates the watchers for the current scope. However, the $apply() method is used to evaluate watchers for root scope, that means it’s for all scopes.

Following is the example of using the $apply() function in AngularJS applications.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

<html> 

<head> 

    <title>AngularJS Apply Example</title>

   <script src="lib/angular.js"></script> 

   <script> 

        var myapp = angular.module("myapp", []); 

        var myController = myapp.controller("myController", function 

        ($scope) { 

               $scope.datetime = new Date(); 

              $scope.updateTime = function () { 

                 $scope.datetime = new Date(); 

                             } 

       //outside angular context          document.getElementById("updateTimeButton").addEventListener('click', function () { 

//update the value 

$scope.$apply(function () { 

          console.log("update time clicked"); 

          $scope.datetime = new Date(); 

          console.log($scope.datetime); 

  }); 

}); 

}); 

</script> 

</head> 

<body ng-app="myapp" ng-controller="myController"> 

      <button ng-click="updateTime()">Update time - ng-click</button>   

      <button id="updateTimeButton">Update time</button> 

<br />

   {{datetime | date:'yyyy-MM-dd HH:mm:ss'}} 

</body> 

</html>  

 Q-41. Which One Handles Exception Automatically Between $Digest And $Apply?.

When an error occurs in one of the watchers, $digest() cannot handle them via $exceptionHandler service. In that case, you have to handle the exception yourself. However, $apply() uses try catch block internally to handle errors. But, if an error occurs in one of the watchers, then it transfers the errors to $exceptionHandler service.

Code for $apply() function.

JavaScript

1

2

3

4

5

6

7

8

9

$apply(expr) { 

      try { 

           return $eval(expr); 

            } catch (e) { 

                   $exceptionHandler(e); 

                } finally { 

                      $root.$digest();

 } 

}

 Q-42. Explain $Watch(), $Watchgroup() And $WatchCollection() Functions Of Scope?

A) $Watch.

Its use is to observe the changes in the variable on the $scope. It accepts three arguments – expression, listener, and equality object. The listener and Equality object are optional parameters.

JavaScript

1

$watch(watchExpression, listener, [objectEquality])

Here, <watchExpression> is the expression to be observed in the scope. This expression gets called on every $digest() and returns a value for the listener to monitor.

The listener defines a function which gets called when watchExpression changes its value. In case, its value does not change then the listener will not be called. The objectEquality is a boolean type to compare the objects for equality using angular.equals.

JavaScript

1

2

3

4

scope.name = 'shailendra'; 

scope.counter = 0; 

scope.$watch('name', function (newVal, oldVal) { 

        scope.counter = scope.counter + 1; }); 

B) $Watchgroup.

This function was introduced in Angular1.3. It works in the same way as $watch() function except that the first parameter is an array of expressions.

JavaScript

1

$watchGroup(watchExpression, listener) 

The listener is also an array containing the new and old values of the variables that are being watched. The listener gets called whenever any expression contained in the watchExpressions array changes.

JavaScript

1

2

3

4

5

6

7

8

9

$scope.teamScore = 0; 

$scope.time = 0; 

$scope.$watchGroup(['teamScore', 'time'], function(newVal, oldVal) {   

     if(newVal[0] > 20){ 

                 $scope.matchStatus = 'win'; 

 else if (newVal[1] > 60){ 

                  $scope.matchStatus = 'times up'; 

}); 

C) $WatchCollection.

This use of this function is to watch the properties of an object. It gets fired when there is any change in the properties. It takes an object as the first parameter and watches the properties of the object.

JavaScript

1

$watchCollection(obj, listener) 

The listener is called whenever there is any change in the obj.

JavaScript

1

2

3

4

5

$scope.names = ['shailendra', 'deepak', 'mohit', 'kapil']; 

$scope.dataCount = 4; 

$scope.$watchCollection('names', function (newVal, oldVal) {    

       $scope.dataCount = newVal.length; 

});

Q-44. How Do You Exchange Data Among Different Modules Of Your Angular JS Application?.

There are a no. of ways in Angular to share data among modules. A few of them are as follows.

The most common method is to create an Angular service to hold the data and dispatch it across the modules.

Angular has a matured event system which provides $broadcast(), $emit() and $on() methods to raise events and pass data among the controllers.

We can also use $parent, $nextSibling, and $ controllerAs to directly access the controllers.

Variables defined at the root scope level ($rootScope) are available to the controller scope via prototypical inheritance. But they behave like globals and hard to maintain.

 Q-45. How Would You Use An Angular Service To Pass Data Between Controllers? Explain With Examples?.

Using a service is the best practice in Angular to share data between controllers. Here is a step by step example to demonstrate data transfer.

We can prepare the data service provider in the following manner.

JavaScript

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

  var dataSet = [];

 

  var addData = function(newData) {

      dataSet.push(newData);

  };

 

  var getData = function(){

      return dataSet;

  };

 

  return {

    addData: addData,

    getData: getData

  };

 

});

Now, we’ll inject the service dependency into the controllers.

Say, we have two controllers – pushController and popController.

The first one will add data by using the data service provider’s addData method. And the latter will fetch this data using the service provider’s getData method.

JavaScript

1

2

3

4

5

6

7

8

9

app.controller('pushController', function($scope, dataService) {

    $scope.callToAddToProductList = function(currObj){

        dataService.addData(currObj);

    };

});

 

app.controller('popController', function($scope, dataService) {

    $scope.dataSet = dataService.getData();

});

 Q-48. What Would You Do To Limit A Scope Variable To Have One-Time Binding?

By prefixing the “::” operator to the scope variable. It’ll make sure the candidate is aware of the available variable bindings in AngularJS. 

Q-49. What Is The Difference Between One-Way Binding And Two-Way Binding?

The main difference between one-way binding and two-way binding is as follows.

In one-way binding, the scope variable in the HTML gets initialized with the first value its model specifies.

In two-way binding, the scope variable will change its value whenever the model gets a different value.

Q-50. Which Angular Directive Would You Use To Hide An Element From The DOM Without Modifying Its Style?.

It is the conditional ngIf Directive which we can apply to an element. Whenever the condition becomes false, the ngIf Directive removes it from the DOM.