Angular.js Interview Questions

           Brush Up with Angular.JS


Made a note of important links and interview questions while preparing with Angular.js 

1) How Angular bootstraps and different ways of bootstrapping.

Bootstrapping is the equivalent of initializing, or starting, your Angular app. There are 2 main ways to do so.

The first is automatically bootstrapping by adding ng-app to the an element in your HTML, like so:
<html ng-app="myApp">
<body ng-controller="myCtrl">
{{msg}}
</body>
</html>

The second would be to bootstrap from the JavaScript, like so, after having creating your app through

 angular.module("myApp", []);
var app = angular.module("myApp", []);
angular.bootstrap(document, ['myApp']);
common controller initialization in both the cases:-
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope){
$scope.msg = "Morgan"
});
Advantages of angular bootstrap:-
1) The declarative process is easier to understand.
2) You can package code as reusable modules.
3) The modules can be loaded in any order (or even in parallel) because modules delays execution.
4) Unit tests only have to load relevant modules, which keeps them fast.
5) End-to-end tests can use modules to override configuration.

More info :-  http://stackoverflow.com/questions/21058213/what-is-meant-by-bootstrapping-in-angular-js

===================================================================

2) Why Angular is called MV*.

MVC - Model-View-Controller
MVP - Model-View-Presenter
MVVM - Model-View-ViewModel
MVW / MV* - Model-View-Whatever

More info :- http://stackoverflow.com/questions/13329485/mvw-what-does-it-stand-for

===================================================================

3) Different kinds of bindings in Angular.

Binding Using Brackets {{message}}
Binding Using ng-bind < div ng-bind ="message"></div>
    One-Time Binding {{::message}}

More info :- https://thinkster.io/a-better-way-to-learn-angularjs/binding

===================================================================

4) How the digest cycle works and ways to avoid watchers.

Order of calling digest cycle:-
$scope.$digest --> $scope.$apply --> $rootscope.$digest
$scope.$watch('aModel', function (newValue , oldValue ){
//updates DOM with new Value
})
$watch --> is a listener function

At a minimum, $digest will run twice even if your listener functions don’t change any models.
It runs once more to make sure the models are stable and there are no changes.

More info :-  https://www.sitepoint.com/understanding-angulars-apply-digest

===================================================================

5) Dependency injection working

Why Dependency Injection?
Modularizing your application makes it easier to reuse, configure and test the components in your application.

AngularJS contains the following core types of objects and components:-
Value (VFS can be injected in .run)
Factory
Service
Provider (initiated by .config)(+Provider as suffix.suffix tells AngularJS to inject the provider itself)
Constant (can be injected in .config)
These core types can be injected into each other using AngularJS dependency injection mechanism.

Service:-
A service in AngularJS is a singleton JavaScript object which contains a set of functions.
The functions contain whatever logic is necessary for the service to carry out its work.
Services in AngularJS are created using the new keyword. Thus, AngularJS will do this internally:

var theService = new MyService();

Example:-
//Injecting values into a service:-

var myModule = angular.module("myModule",[])
myModule.value("myValue", "test")
function MyService(myValue){
this.doIt = function(){
console.log ("value" + myValue) } }
myModule.service("myservice", MyService)
// Inject a service into a controller
myModule.controller("MyController", function($scope, myService) {
    myService.doIt();
});

More info :- http://tutorials.jenkov.com/angularjs/dependency-injection.html

===================================================================

6) Ways to share data between controllers and directives.

The above example shows sharing data using $rootscope , which isn't a good practice

You can use a shared Service/Factory with the data you want to share b/w controllers and directives

More info :-https://raw.githubusercontent.com/hanumesh/Angularday2/master/hero_rootscope_passing_data.html
http://plnkr.co/edit/Q1VdKJP2tpvqqJL1LF6m?p=preview

===================================================================

7) Difference between Service and Factory

Key points :-
Service internally uses factory, Service calls a predefined factory.
It uses this keyword, it's basically constructor creation

In factory, we return an user defined object.


More Info :-
https://blog.thoughtram.io/angular/2015/07/07/service-vs-factory-once-and-for-all.html

===================================================================

8) Properties of custom directives and its usage.

compile:- For AngularJS, "compilation" means attaching directives to the HTML to make it interactive
$compile can match directives based on element names, attributes, class names, as well as comments.
You do not currently have the ability to access scope variables from the templateUrl function, since the template is requested before the scope is initialized.
When you create a directive, it is restricted to attribute and elements only by default. In order to create directives that are triggered by class name, you need to use the restrict option.
The restrict option is typically set to:
'A' - only matches attribute name
'E' - only matches element name
'C' - only matches class name
'M' - only matches comment
These restrictions can all be combined as needed:
'AEC' - matches either attribute or element or class name
only use transclude: true when you want to create a directive that wraps arbitrary content.
use controller when you want to expose an API to other directives. Otherwise use link.
The basic difference is that controller can expose an API, and link functions can interact with controllers using require.
Use the compile function for template DOM manipulation only. Use the link function whenever you want to add behavior.

More info :- 
http://tutorials.jenkov.com/angularjs/custom-directives.html

https://docs.angularjs.org/guide/directive

===================================================================

9)  What do you mean by Isolate scope ?

a) @
The scope definition using @text is binding the text model to the directive’s attribute. Note that any changes to the parent scope text will change the local scope text, but not the other way around.

<my-widget2 text="Hello World"></my-widget2>
app.directive("myWidget2", function() {
  return {
    restrict: "E",
    template: "<p></p>",
    scope: {
      text: "@text"
    }
  };
});


b)  =bindToThis
If you want instead to have a bi-directional binding between the parent scope and the local scope, you should use the = equality character.
 Changes to the local scope will also change the parent scope

<my-widget2 text="Hello World"></my-widget2>
app.directive("myWidget2", function() {
  return {
    restrict: "E",
    template: "<p></p>",
    scope: {
      text: "=text"
    }
  };
});

c) & (& bindings are ideal for binding callback functions to directive behaviors.)
 use &attr in the scope option when you want your directive to expose an API for binding to behaviors.

We pass the attribute fn to the directive and since the local scope defines fn accordingly we can call the function in the linkFunction and pass in the expression arguments as a hash.

<my-widget-expr fn="count = count + 1"></my-widget-expr>
app.directive("myWidgetExpr", function() {
  var linkFunction = function(scope, element, attributes) {
    scope.text = scope.fn({ count: 5 });
  };
  return {
    restrict: "E",
    template: "<p></p>",
    link: linkFunction,
    scope: {
      fn: "&fn"
    }
  };
});

More info:-
http://tutorials.jenkov.com/angularjs/custom-directives.html
 http://jsfiddle.net/simpulton/SPMfT/
http://stackoverflow.com/questions/14050195/angularjs-what-is-the-difference-between-and-in-directive-scope
===================================================================

10) When to use Broadcast and emit services

$scope.$emit('eventName', { message: msg });
$scope.$broadcast('eventName', { message: msg });
$scope.$on('eventName', function (event, args) {
$scope.message = args.message;
});

More info:-
http://www.dotnet-tricks.com/Tutorial/angularjs/HM0L291214-Understanding-$emit,-$broadcast-and-$on-in-AngularJS.html
===================================================================

11 ) Ways to improve performance of an angular js application.

console.timeEnd('digest') in chrome console

 More info:-
 http://www.alexkras.com/11-tips-to-improve-angularjs-performance
 http://www.codelord.net/2014/06/17/angular-performance-101-slides/ 

===================================================================

12) What is SPA and how angular helps in creating SPA's.
:-  Routing capabilities of angular

===================================================================

13) Name directives in Angular and its uses.
:-
ng-app directive defines where in our page an Angular application is running
ng-model is a directive in AngularJS that binds a variable from an input field to a scope variable.
ng-init is a directive that evaluates the given expression once when the element is initialized.
ng-strict-di directive will ensure that all services in your application are properly annotated.
ng-hide, ng-checked, ng-mouseente are others

===================================================================
14) Routing and state logic's.

UI-Router info ,:- https://scotch.io/tutorials/angular-routing-using-ui-router

var routerApp = angular.module('routerApp', ['ui.router']);
routerApp.config(function($stateProvider, $urlProvider){
$urlProvider.otherwise('/home');
$stateProvider
.state('home'{
url : '/home',
"templateUrl" : 'partial-home.html'
})
.state('about',{
})
})


More info:-
  http://fdietz.github.io/recipes-with-angular-js//backend-integration-with-node-express/implementing-client-side-routing.html 

===================================================================

15) Filters Example:-
Angular Filters are typically used to format expressions in bindings in your template. They transform the input data to a new formatted data type.

<body ng-app="myApp">
<ul ng-init="names"=["1", "2", "3", "4"]>
<li ng-repeat="name in names" | exclude :"2">
<span>{{name}}</span>
</li>
</ul>
</body>

app.filter('exclude',function(){
return function (input,exclude){
var result = [];
for (i=0; i<input.length; i++){
if (input[i] !== exclude){
result.push(input[i])
}
}
return result;
}
})
var app = angular.module("myApp", [])



===================================================================

16)  Forms:-

The novalidate attribute disables the HTML5 validations, which are client-side validations supports by modern browsers.
In our example we only want the Angular.js validations running to have complete control over the look and feel.
Validating a Form Model Client-Side is an important aspect of forms

===================================================================//  // 17) consuming external services

 // Requesting JSON data with AJAX


<body ng-app="MyApp">
  <div ng-controller="PostsCtrl">
    <ul ng-repeat="post in posts">
      <li>{{post.title}}</li>
    </ul>
  </div>
</body>

var app = angular.module("MyApp", []);
app.controller("PostsCtrl", function($scope, $http) {
  $http.get('data/posts.json').
    success(function(data, status, headers, config) {
      $scope.posts = data;
    }).
    error(function(data, status, headers, config) {
      // log error
    });
});


===================================================================

18) jquery sample example

var main = function(){
$('.dropdown-toggle').click(function(){
$('.dropdown-menu').toggle();
});
}
$(document).ready(main)
 
/*jquery enables us to do 3 main things
EVENTS- Respond to user interactions
DOM Manipulation - Modify HTML elements on the page
EFECTS - Add animations
*/

// sample Ajax call
$(function(){
$.ajax({
url :'api/links',
data : {},
type : 'POST',
success : function (data){
},
error : function (){
}
})
})

===================================================================

19 ) JWT

a) You can use the token in a URL, POST parameter, or an HTTP header. The versatility of the JSON Web Token let’s us authenticate an API quickly and easily by passing information through the token.

b) JSON is less verbose than XML, when it is encoded its size is also smaller, making JWT more compact than SAML. This makes JWT a good choice to be passed in HTML and HTTP environments.

c) Token based authentication is stateless. We are not storing any information about our user on the server or in a session.

More info:-
https://scotch.io/tutorials/the-anatomy-of-a-json-web-token
===================================================================

Important links to have a note for

http://fdietz.github.io/2015/04/13/day-1-how-to-build-your-own-team-chat-in-five-days.html ( full project )
https://omarfouad.com/  ( gulp )
https://scotch.io/bar-talk/the-best-news-from-angulars-ng-conf-2016#typescript-provides-lots-of-benefits (angular 2)

Comments

Post a Comment

Popular posts from this blog

Set up your VOIP based SIP soft phone and know more about VOIP

Front End Developer Interview quiestions- All in single blog

Data Science v/s Data engineer v/s Data Analyst