Real Time Questions In AngularJS

In this article you will learn about some AngularJS concepts with questions and answer . 

What is a single Page application and how does it differ from web pages?

Normal web pages require a server roundtrip every time to give the output to the page.

A single-page web application however is delivered as one page to the browser and typically does not require the page to be reloaded as the user navigates to various parts of the application. This results in faster navigation, more efficient network transfers and better overall performance for the end user.

  • The application is responsive in the UI with no page flicker
  • The Back/Forward buttons work as expected
  • More JavaScript than actual HTML
  • Dynamic data loading from the server-side API, works with restful web service with JSON format
  • Rich interaction among UI components
  • Less data transfers from the server and most of the page process in the UI occurs client-side.
  • The application contains tabs and subtabs with multiple HTML containers on the click of the tabs or subtabs and the specific portions of the page that are loaded into the page (the page will be one using the application)
  • Applications written in AngularJS are cross-browser compliant. Angular automatically handles the JavaScript code suitable for each browser

How to arrange AngularJS folder and File structure?

In the UI projects we had segregated the application based on the functionalities/features it has. For example, for a banking system we have different modules i.e, Bill Pay, Financial summary, statements, Loans, Cards etc.

For each module we have different folders like:

Controllers: It contains all controller JavaScript files.

Services – We have different kind of services

  • Data Services (Hitting to Database or different external services using $http, or $Q service)
  • Static Data services (Used to initialize static Data)
  • communication Service (Used to set some values to services and used across the app)

Views: it contains the html views and partial views.

Common: It is a folder which has Images, styles, Scripts folder. Scripts folder framework related angular in built scripts.

Directives: We have directives specific to the modules and common directives which is used across all modules, some of them Calendar, File uploader, different controls with validations, some grid customization.

Filter: This folder contains all our custom filters used across the application.

Utility: This is a folder which contains the common data manipulation logic, date formatting as per the logic needed in the applications.

Test: It contains our entire test JavaScript files which are used to test controller and other utility JavaScript files.

  • In the controller we call to the services.
  • Services has the code to hit to the WEB API or WCF, it gets the results and assigned it to the Scope object.
  • The WEBAPI internally calls Data Layer /entity Framework or BO to hit the SQL server and gets the Data.
  • In the controller we assign the data, and we bind the data to UI by reading the model properties

What are the best practices you followed in the angular projects?

These are the best practices we followed in our application

  • Scope holds the source of data and communicates between the components
  • Controller sets up the scope, data does the view interaction and deals with the presentation logic with no business logic
  • View is responsible for displaying the UI by declaring binding and directive
  • Directive does the DOM manipulation and receives view events.
  • Service communicates with the server and gets data and holds the data and state.
  • Used dependency to inject different modules and services in a minified way.
  • Wrote Common directives for common functionality
  • Wrote unit testing
  • Used minified version of the script for deployment purpose
  • For calling multiple services we followed Asynchronous call using $Q
  • Proper namespace to avoid namespace collision and confusion in the script.
  • Used AngularJS versions of JavaScript functionality like $timeout, $interval etc.
  • Avoids too many watchers, one way binding for performance improvement.
How do you handle sessions in the Angular project?

Angular has client side storage using session storage, local storage and cookie storage to handle sessions.

  • Implemented session management technique at the server side from a Database call.
  • Wrote a web service/WCF/WEB API which we call from the front end during the application startup to check whether the client is authenticated if successful return user data in the response in the form of a token otherwise redirect it to login page.
  • Stored those token details in a factory or as an object in $rootScope or a service or $cookie store so you can access it from anywhere.
From the main page to pop up page we use local storage to access the session related data.

How do you maintain security in AngularJS applications?

Mostly we rely on web API or WCF to handle security at the server side. In Angular UI we had implemented security as below.

In the routing we had some code to check user permission. We read user roles and access level from database by using an angular service via web API.

  1. .when('/Accounts',  
  2.     {  
  3.     templateUrl: '/templates/accounts.html',  
  4.     controller: 'accountsController',  
  5.     resolve:   
  6.     {  
  7.         permission: function(authorizationService, $route)   
  8.         {  
  9.             return authorizationService.CheckRoles([roles.user]);  
  10.         },  
  11.     }  
  12. });   

To some extent we follow angular $sanitize service that will parse an HTML string into tokens avoiding cross scripting type of security.

We need to do proper validation both in server side and client side to avoid any kind of security threats like SQL injections or CSRF security. Again we had implemented SSL in IIS level to give more security.

How do you do the error logging in Angular code?

Angular is a client side framework; we cannot write the log into the client side as we are looking to log at the server side for future tracing and diagnostics purpose. Write a service which has a method like this and call this using try and catch block. On exception or error log we can read the logs and call an Ajax post to handle the error and in the web API action we have that code to insert into database logs.

  1. function log(exception)  
  2. {  
  3.     $log.error.apply($log, arguments);  
  4.     $.Ajax  
  5.     ({  
  6.         type: "POST",  
  7.         url: "WebAPI/logError ,  
  8.             //It is a action method in web api code which hits the database and do database log  
  9.         contentType: "application/json",  
  10.         data: angular.toJson  
  11.         ({  
  12.             errorUrl: $window.location.href,  
  13.             errorMessage: errorMessage  
  14.         })  
  15.     });  
  16. }   

Angular Interceptor is also a good way to log errors which can be applied on request error or response error.

How to  fetch the records from SQL server and bind it to the page.

For these types of questions these are the four steps we need to remember,

  1. Write a web API or WCF which will return the data from the database,
    1. public class EmployeeAPIController: ApiController  
    2. {  
    3.     private EmployeeEntities db = new EmployeeEntities();  
    4.     public IEnumerable < Employee > GetEmployees()  
    5.     {  
    6.         return db.Employees.AsEnumerable();  
    7.     }  
    8. }  
  2. Write a service which will have a web API call using $http.get,
    1. app.service('EmployeeService', function($http)   
    2.     {  
    3.     this.getAllEmployee = function()  
    4.       
    5.     {  
    6.         return $http.get("/api/EmployeeAPI");  
    7.     }  
    8. });  
  3. Call the service from the controller,
    1. app.controller('EmployeeController', function($scope, EmployeeService)  
    2.  {  
    3.     function GetAllRecords()  
    4.   {  
    5.         var promiseGet = EmployeeService.getAllEmployee();  
    6.         promiseGet.then(function(pl)   
    7.         {  
    8.                 $scope.Employees = pl.data, $scope.Data = pl.data  
    9.             },  
    10.             function(errorPl)   
    11.             {  
    12.                 $log.error('Some Error in Getting Records.', errorPl);  
    13.             });  
    14.     }  
    15.     $scope.Employees =  
    16.     {  
    17.         data: 'Data'  
    18.     };  
    19. });  
  4. Bind the Scope data in the html as below,
    1. <tr ng-repeat="employee in Employees">  
    2.     <td>{{employee.Name}}</td>  
    3.     <td>{{employee.Department}}</td>  
    4.     <td>{{employee.Salary}}</td>  
    5. </tr>  
What are the different types of calls we can call in $http services?

$http is a service which provides a set of methods to call the outside WCF /web api.These methods are:

  • $http.$get(url): Sends an HTTP GET request to the URL specified.
  • $http.post(url, dataToBePosted): Sends an HTTP POST request to the URL specified.
  • $http.put(url, data): Sends an HTTP PUT request to the URL specified.
  • $http.delete(url): Sends an HTTP DELETE request to the URL specified.

The following is a small snippet showing usage of $http:

  1. $http.get('/api/apimethod').then(function(response)  
  2. {  
  3.     return response.data;  
  4. }, function(error)  
  5. {  
  6.     return error;  
  7. });   
What are the Angular JS interceptors?

(or)How do you inject custom logic in the request and response cycle?

In a request and response communication of a HTTP call if we want to inject some custom logic the HTTP Interceptor comes into picture. HTTP Interceptors executes some custom logic before or after the HTTP call.

For example, when appending the authentication token to every HTTP request that token is generated from the client who needs to be validated at the server for security purposes.

These interceptors act as a hook up for the HTTP calls.

HTTP Interceptors are used for adding custom logic for authentication, authorization, session/state management, logging, modifying Response, URL rewriting, Error handling, Caching, adding custom header, timestamp in the request /response, encrypting and decrypting the request and response information or manipulating the request and response data over the request cycles.

How to write custom directive in AngularJS  and call it in the html page?

Custom directives  are the key elements in angular projects  where we have to achieve common functionalities. Some of these are Date picker calendar control, File upload controller, all sorts of validation like allowing a textbox only numeric characters, or a textbox with text only, loader or spinning symbol, etc. 
Below is the syntax and a custom directive example, 
  1. myModule.directive("directiveName", function(injectables component)   
  2. {  
  3.     return   
  4.     {  
  5.         restrict: "A/E/C/M"// It applies to Attribute or Element or Class or Comment  
  6.         template: "<div></div>"// Html to be added  
  7.         templateUrl: "directive.html"// template to be added  
  8.         replace: false// replace yes/No  
  9.         transclude: false// Transclude yes/No  
  10.         scope: false// Current scope or isolated scope  
  11.         require: ["someOtherDirective"], // if any other directive is needed  
  12.         controller: function($scope, $element, $attrs, $transclude, otherInjectables)  
  13.         {...  
  14.         }, // controller  
  15.         link: function postLink(scope, iElement, iAttrs)   
  16.         {...  
  17.         },  
  18.         priority: 0, //Priority of directive  
  19.         terminal: false,  
  20.         compile: function compile(tElement, tAttrs, transclude)  
  21.          {  
  22.             return  
  23.             {  
  24.                 pre: function preLink(scope, iElement, iAttrs, controller)  
  25.                 {...  
  26.                 },  
  27.                 post: function postLink(scope, iElement, iAttrs, controller)  
  28.                  {...  
  29.                     } // compile functions  
  30.             }  
  31.         }  
  32.     };  
  33. });   

  1. <!DOCTYPE html>  
  2. <html ng-app="myApp">  
  3.   
  4. <head>  
  5.     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  6.     <script>  
  7.         var myapp = angular.module('myApp', [])  
  8.         myapp.directive('firstDirective', function()   
  9.         {  
  10.             return   
  11.             {  
  12.                 template: ' <  
  13.                     h3 > I am From custom directive!!! < /h3>'  
  14.             };  
  15.         });  
  16.     </script>  
  17. </head>  
  18.   
  19. <body>  
  20.     <div ng-app="myApp">  
  21.         <div>  
  22.             <div>  
  23.                 <first-directive>  
  24.             </div>  
  25.         </div>  
  26.     </div>  
  27. </body>  
  28.   
  29. </html>  

How to use controller in angular?

Controllers are simple java script functions which control data and logic to HTML in the page. We need to declare the controller in which section  it applies to the page. For example if we have a controller named myCtrl and it is defined in the module as below.

  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
  4.   
  5. <body>  
  6.     <div ng-app="myApp" ng-controller="myCtrl">  
  7.         First Name: <input type="text" ng-model="firstName"><br> Last Name: <input type="text" ng-model="lastName"><br>  
  8.         <br> Full Name: {{firstName + " " + lastName}}</div>  
  9.     <script>  
  10.         var app = angular.module('myApp', []);  
  11.         app.controller('myCtrl', function($scope)   
  12.          {  
  13.             $scope.firstName = "Pradeep";  
  14.             $scope.lastName = "Sahoo";  
  15.         });  
  16.     </script>  
  17. </body>  
  18.   
  19. </html>   

What is ng-include and when to use it in angular projects?

ng-include is a directive which is used to include HTML contents from other files into the view's HTML template.

For example, if we want to include top, bottom, left and right side bars in the page we need to write it as,

  1. <div ng-include src="'views/leftsidebar.html'"></div>  
  2. <div ng-include src="'views/rightsidebar.html'"></div>  
  3. <div ng-include src="'views/topsidebar.html'"></div>  
  4. <div ng-include src="'views/bottomsidebar.html'"></div>   

What is Isolate Scope and why it is required ?

By default, directives have access to the parent scope in Angular apps. When the parent scope changes at the entire directivethey are no longer useful.

The shared scope allows the parent scope to flow down into the directive but the Isolate scope doesn’t allow the parent scope to flow down into the directive. If you want to make a reusable directive you can’t rely on the parent scope and must use something called Isolate Scope instead. Isolated scope is written as scope: {}

Example of code snippet:

  1. angular.module('mydirective').directive('sharedScope', function()  
  2. {  
  3.     return   
  4.     {  
  5.         scope: {},  
  6.         template: 'Name: {{emp.name}} Address: {{emp.address}}'  
  7.     };  
  8. });   

How to apply validation in AngularJS?

The angular framework is rich in validation .Below is the code for how to achieve a simple validation.
  1. <!DOCTYPE html>  
  2. <html>  
  3. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>  
  4.   
  5. <body>  
  6.     <h2>  
  7. Validation Example</h2>  
  8.     <form ng-app="myApp" ng-controller="validateCtrl" name="myForm" novalidate>  
  9.         <table style="border: 1px solid gray; width: 500px;">  
  10.             <tr>  
  11.                 <td colspan="2">  
  12.                     <span style="color: red; padding-left: 100px; border: 3px;">Log In </span>  
  13.                 </td>  
  14.             </tr>  
  15.             <br />  
  16.             <tr>  
  17.                 <td>  
  18.                     Username:  
  19.                 </td>  
  20.                 <td>  
  21.                     <input type="text" name="user" ng-model="user" required>* <span style="color: red" ng-show="myForm.user.$dirty && myForm.user.$invalid"><span ng-show="myForm.user.$error.required">  
  22. Username is required.</span> </span>  
  23.                 </td>  
  24.             </tr>  
  25.             <tr>  
  26.                 <td>  
  27.                     Email:  
  28.                 </td>  
  29.                 <td>  
  30.                     <input type="email" name="email" ng-model="email" required>* <span style="color: red" ng-show="myForm.email.$dirty && myForm.email.$invalid"><span ng-show="myForm.email.$error.required">  
  31. Email is required.</span> <span ng-show="myForm.email.$error.email">Invalid email address.</span>  
  32.                     </span>  
  33.                 </td>  
  34.             </tr>  
  35.             <tr>  
  36.                 <td colspan="2">  
  37.                     <p>  
  38.                         <input type="submit" ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||  
  39. myForm.email.$dirty && myForm.email.$invalid">  
  40.                     </p>  
  41.                 </td>  
  42.             </tr>  
  43.         </table>  
  44.     </form>  
  45.     <script>  
  46.         var app = angular.module('myApp', []);  
  47.         app.controller('validateCtrl', function($scope) {  
  48.             $scope.user = 'Pradeep K';  
  49.             $scope.email = '[email protected]';  
  50.         });  
  51.     </script>  
  52. </body>  
  53.   
  54. </html>  

How to do custom form validation in AngularJS?

To achieve the custom form validation we need to write directives. For Example we want to show the number of characters left for a text area when the user enters text to a text area.

Code Example:
  1. <!DOCTYPE html>  
  2. <html ng-app="myapp" xmlns="http://www.w3.org/1999/xhtml">  
  3.   
  4. <head>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>  
  6.     <script>  
  7.         var $scope;  
  8.         var app = angular.module('myapp', []);  
  9.         app.controller('Ctrl', function($scope)   
  10.         {  
  11.             $scope.wks =   
  12.             {  
  13.                 number: 1,  
  14.                 validity: true  
  15.             }  
  16.         });  
  17.         app.directive('isNumber', function()   
  18.                         
  19.         {  
  20.             return   
  21.             {  
  22.                 require: 'ngModel',  
  23.                 link: function(scope)   
  24.               {  
  25.                     scope.$watch('wks.number', function(newValue, oldValue)   
  26.                     {  
  27.                         var arr = String(newValue).split("");  
  28.                         if (arr.length === 0) return;  
  29.                         if (arr.length === 1 && (arr[0] == '-' || arr[0] === '.')) return;  
  30.                         if (arr.length === 2 && newValue === '-.'return;  
  31.                         if (isNaN(newValue))   
  32.                         {  
  33.                             scope.wks.number = oldValue;  
  34.                         }  
  35.                     });  
  36.                 }  
  37.             };  
  38.         });  
  39.     </script>  
  40. </head>  
  41.   
  42. <body ng-app="myapp">  
  43.     <form ng-app="myapp" name="myform" novalidate>  
  44.         <div ng-controller="Ctrl"></div>  
  45.         <textarea ng-model="test" ng-trim="false" maxlength="100"></textarea>  
  46.         <span>{{100 - test.length}} left</span>  
  47.     </form>  
  48. </body>  
  49.   
  50. </html> .

What is a custom filter, write a own custom filter

Custom Filters are used to extend the behavior of binding expressions based on our own logic.

Example:

  1. angular.module("testModule").filter("currencyFilter", function()  
  2. {  
  3.     return function(val)   
  4.     {  
  5.         return "Rs. " + val * 67;  
  6.     };  
  7. });  
  8. In the HTML use it as:  
  9.     <  
  10.     span >   
  11.     {  
  12.         {  
  13.             price | currencyFilter  
  14.         }  
  15.     } < /span>   

How to do DOM manipulation inside a directive?

DOM manipulations are done in custom directive.

Here is a Code example,

  1. app.directive('myDirective', function()  
  2. {  
  3.     return  
  4.     {  
  5.         restrict: 'A',  
  6.         templateUrl: 'directives/template.html',  
  7.         link: function(scope, element, attr)  
  8.         {  
  9.             $(element).css('font-weight''bold');  
  10.         }  
  11.     };  
  12. });   

How to communicate between the controllers in AngularUI Pages ?

Angular provides the $broadcast, $on and $emit services for event-based communication among controllers. This is very similar to the publisher subscriber pattern.

We can use root scope or service to pass data across controllers:

  • $broadcast: dispatches the event downwards to all child scopes.
  • $emit: dispatches the event upwards using the scope hierarchy.
  • $on: listen on the events of a given type. It can catch the event dispatched by $broadcast and $emit.

What are the Angular 2.0 new features in compared to angular previous versions?

There are drastic changes in 2.0 in compared to earlier 1.x versions .Some of the new features are

  • Component Based routing
  • No Scope use
  • Directive based manipulation
  • More test support

Can you explain Angular 2.0 routing and how it is defined?

Angular 2.0 comes up with folder based structures as component.ng-viewport is the place holder where we will load the content of the page.

Let us consider we have different Tabs, such as news, stock, whether, stocks. On click of each tab we will load different views.

This is the code we need to follow.

  1. <body ng-controller="ComponentController">  
  2.     <h1>  
  3. Component Wise Routing in Angular Js</h1>  
  4.     <a ng-link="news()" class="tab">News</a>  
  5.     <a ng-link="stock()" class="tab">Stock</a>  
  6.     <a ng-link="weather()" class="tab">Weather</a>  
  7.     <a ng-link="sports()" class="tab">Sports</a>  
  8.     <div ng-viewport>  
  9.     </div>  
  10.     <script>  
  11.         var module = angular.module("myApp", ["ngNewRouter""myApp.news""myApp.stock""myApp.weather""myApp.sports"]);  
  12.         module.controller("ComponentController", function($scope, $router) {  
  13.             $router.config(  
  14.             [{  
  15.                 path: "/",  
  16.                 redirectTo: "news"  
  17.             },   
  18.             {  
  19.                 path: "/stock",  
  20.                 component: "stock"  
  21.             },   
  22.             {  
  23.                 path: "/weather",  
  24.                 component: "weather"  
  25.             },   
  26.             {  
  27.                 path: "/sports",  
  28.                 component: "sports"  
  29.             }]);  
  30.         });  
  31.     </script>  
  32.     <script src="components/news/news.js"></script>  
  33.     <script src="components/stock/stock.js"></script>  
  34.     <script src="components/weather/weather.js"></script>  
  35.     <script src="components/sports/sports.js"></script>  
  36. </body>   

ng-viewport

In order to inject an HTML template known as component into a web page, we need to create a container/placeholder div for it. This div should have an Angular directive ng-viewport. This ng-viewport is like ng-view/ui-view from Angular UI router and AngularJS core functionality. The directive ng-viewport can be used any number of times inside an application.

Component

This is an Angular service which allows us to retrieve the current set of route parameters. Componet looks for components folder inside the project structure.

In the Angular code how to avoid the error “is not allowed by Access-control-Allow-Origin”?

To enable CORS in Web API, use the Microsoft.AspNet.WebApi.Cors package, which is available on NuGet.

config.Enablecors() to the register() in the WebAPIconfig.cs

How to bind a data to the ng-grid ?

Showing the Data in grid and editing and deleting records in a grid is a common requirement in a project.

  1. var app = angular.module('myApp', ['ngGrid']);  
  2. app.controller('MyCtrl', function($scope)  
  3. {  
  4.     $scope.myData = [{  
  5.         name: "Moroni",  
  6.         age: 50  
  7.     }, {  
  8.         name: "Tiancum",  
  9.         age: 43  
  10.     }, {  
  11.         name: "Jacob",  
  12.         age: 27  
  13.     }, {  
  14.         name: "Nephi",  
  15.         age: 29  
  16.     }, {  
  17.         name: "Enos",  
  18.         age: 34  
  19.     }];  
  20.     $scope.gridOptions =   
  21.     {  
  22.         data: 'myData',  
  23.         columnDefs: [  
  24.         {  
  25.             field: 'name',  
  26.             displayName: 'Name'  
  27.         },   
  28.         {  
  29.             field: 'age',  
  30.             displayName: 'Age'  
  31.         }]  
  32.     };  
  33. }); <  
  34. body ng - controller = "MyCtrl" >  
  35.     <  
  36.     div class = "gridStyle"  
  37. ng - grid = "gridOptions" > < /div> <  
  38.     /body>   

These are some of the concepts and real time questions. Thanks for reading!

Read more articles on AngularJS:


Similar Articles