Sunday 12 February 2017

Interview question one line on AngularJS

Sl No Questions Keyword Answer Example
1 What is AngularJS ? Angular is a declarative JavaScript framework to simply JavaScript code
2 Explain Directives in Angular? Directives are attributes decorated on the HTML elements. All directives start with the word “ng” ngBind,
ngModel
ngClass
ngApp
ngInit
ngRepeat
3 Explain ng-app It is the most important directive for an Angular Application, which is used to indicate starting of an Angular Application to AngularJS
4 Explain ng-init ng-init directive is used to initialize an AngularJS Application data variable's inline statement <body ng-app="myApp" ng-init="pi=3.14">
The value of pi is {{pi}}
</body>
5 Explain ng-model ng-model directive is used to define the model/variables value to be used in AngularJS Application’s HTML controls like <input type=’text’/>
It also provides two-way binding behavior with the model value
6 Explain ng-bind ng-model directive is used to define the model/variables value to be used in AngularJS Application’s HTML controls like <input type=’text’/>
It also provides one-way binding behavior with the model value
7 Explain ng-repeat ng-repeat directive is used to repeat HTML statements
8 What are controllers and need of ng-controller and ng-model in Angular? “Controllers” are simple javascript function which provides data and logic to HTML UI function Customer($scope)
{
        $scope.CustomerName = "Shiv";
        $scope.CustomerCode = "1001";
        $scope.Add = function () {
        }
        $scope.Update = function () {
        }
}

<div ng-controller="Customer">
<input type=text id="CustomerName"  ng-model="CustomerName"/><br />
<input type=text id="CustomerCode"  ng-model="CustomerCode"/>
</div>
9 What are expressions in Angular? code which resolves to value or to display the variable {{1+1}}
10 How can we initialize Angular application data? We can use “ng-init” directive to achieve the same <body ng-app="myApp" ng-init="pi=3.14">
The value of pi is {{pi}}
</body>
11 Explain $scope in Angular? “$scope” is an object instance of a controller
and it is an angular service for Angular scope management
12 What is “$rootScope” and how is it related with “$scope”? “$rootScope” is a parent object of all “$scope” angular objects created in a web page.
13 Explain the concept of digest cycle, watchers and dirty checking? Digest cycle: - It is a simple loop which updates the model and view.
Watchers :- They are listeners which are attached to expression and angular directives and fire when the model data changes.
Dirty check :- This is a extra digest loop which runs to check any cascading left over updates due to the first digest cycle.
14 What can be the performance implications of watchers and digest cycle ? As per AngularJS team having more than 2000 watchers on Angular screen is a bad practice.
15 How can we measure no: of watchers & time spent on digest cycle? Batrang tool from Google extension
16 How can we decrease digest cycle time ? Remove unnecessary watchers.
Use one time Angular binding. Especially if you see ng-repeat loop apply one time binding.
17 Can we force the digest cycle to run manually? $scope.apply()
18 Do I need jquery for Angular? No
19 How is the data binding in Angular ? Two way binding
20 Explain compile and link phase? Angular parser works in 3 steps:-
Step 1:- HTML browser parses the HTML and creates a DOM (Document Object Model).
Step 2:- Angular framework runs over this DOM looks at the Angular directives and manipulates the DOM accordingly.
Step 3:- This manipulated is then rendered as HTML in the browser
21 How do we make HTTP get and post calls in Angular? “$http” service API needs atleast three things:-

First what is the kind of call “POST” or “GET”.
Second the resource URL on which the action should happen.
Third we need to define the “success” function which will be executed once we get the response from the server.
function CustomerController($scope,$http)
{
 $scope.Add = function()
 {
            $http({
                 method: "GET",
                url: "http://localhost:8438/SomeMethod"
           }).success(function (data, status, headers, config)
  {
                   // Here goes code after success
  }
 }
}
22 How do we pass data using HTTP POST in Angular ? You need to pass data using the “data” keyword in the “$http” service API function Var myData = {};
myData.CustomerName = “Test”;
$http({ method: "POST",
 data: myData,
 url: "http://www.xyz.com"})
 .success(function (data, status, headers, config)
 {
   // Here goes code after success
 })
23 What is dependency injection and how does it work in Angular? Dependency injection is a process where we inject the dependent objects rather than consumer creating the objects function CustomerController($scope,$http)
{
// your consumer would be using the scope and http objects
}
24 How does DI benefit in Angular? There are two benefits of DI
1) Decoupling
2) Testing
25 What are services in Angular? Service helps to implement dependency injection.
26 Are Service object instances global or local? Global
27 What is a Factory in Angular? the purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object var app = angular.module("myApp", []); // creating a APP
app.controller("CustomerController", CustomerController); // Register the VM
app.factory("Customerfactory", CreateCustomer);
28 What is the difference between Factory and Service? AngularJS Service: is used for sharing utility functions with the service reference in the controller. Service is singleton in nature so for once service only one instance is created in the browser and the same reference is used throughout the page

AngularJS Factory: the purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object
29 How are validations implemented in Angular? !frm1.CustomerName.$valid
30 How to check error validation for a specific field? !frm1.CustomerName.$valid
31 What does SPA (Single page application) mean? SPA is a concept where rather loading pages from the server by doing post backs we create a single shell page or master page and load the webpages inside that master page
32 How can we implement SPA with Angular? Angular-route.js or Angular-ui-route.js
33 How to implement routing in Angular? Step 1: - End user clicks on a hyperlink or button and generates action.
Step 2: - This action is routed to the route provider.
Step 3: - Router provider scans the URL and loads the view in the place holder defined by “ng-view” attribute.
Step 1: - Add the “Angular-route.js” file to your view.
<script src="~/Scripts/angular-route.js"></script>
Step 2: - Inject “ngroute” functionality while creating Angular app object.
var app = angular.module("myApp", ['ngRoute']);
Step 3: - Configure the route provider.
app.config(['$routeProvider',
            function ($routeProvider) {
                $routeProvider.
                        when('/Home', {
                            templateUrl: 'Yoursite/Home',
                            controller: 'HomeController'
                        }).
                        otherwise({
                            redirectTo: '/'
                        });
            }]);
Step 4: - Define hyperlinks.
<div>
<a href="#/Home">Home</a><br />
<a href="#/Search"> Search </a><br />
</div>
Step 5: - Define sections where to load the view.
<div ng-view>

</div>
34 How to implement SPA using angular-UI route? myApp.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('Home', {
            url: '/HomePage',
            templateUrl: 'Home.htm'
        })
        .state('About', {
url: '/About',
            templateUrl: 'About.htm'
        })};

<a ui-sref="About" href="#About">Home</a>
<a href="#Home">About</a>
<ui-view></ui-view>
35 Can we load HTML content rather than a full page ? using “template” property myApp.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
          .state('About', {
url: '/About',
template: '<b>This is About us</b>'
        })};
36 How can we create controllers and pass parameters in Angular UI route? myApp.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state('State1', {
            url: '/SomeURL/{Id:[0-9]{4,4}}',
            template: '<b>asdsd</b>',
            controller: function ($scope, $stateParams) {
                alert($stateParams.Id);
            }
        });
37 How to implement nested views using Angular UI route? myApp.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
        .state(“View”, {
            templateUrl: 'View.htm'
        })
        .state('View.SubView1', {
            template: '<b>Sub view 1</b>'
        }).state('View.SubView2', {
            template: '<b>Sub view 2</b>'
        });
});

<a ui-sref="View.SubView1" href="#View.SubView1">Sub view 1</a>
<a ui-sref="View.SubView2" href="#View.SubView1 ">Sub view 2</a>
<div ui-view></div>
38 How can we create a custom directive in Angular? app.directive('companyCopyRight', function ()
{
return
{
        template: '@CopyRight   dotnet-professional-amit.blogspot.in/'
 };
});

<div ng-controller="CustomerViewModel">
<div company-copy-right></div>
</div>
39 What kind of naming conventions is used for custom directives? camelCase
40 What are the different custom directive types in AngularJS? Element directives (E)
Attribute directives (A)
CSS class directives (C)
Comment directives (M)
myapp.directive('userinfo', function()
{
    var directive = {};
    directive.restrict = 'E';
    directive.template = "User : {{user.firstName}} {{user.lastName}}";
    return directie;
});

// Element
<userinfo></userinfo>
// Attribute
<div userinfo></div>
41 What if I want custom directives to be applied on element as well as attributes ? directive.restrict = 'EA'; directive.restrict = 'EA';
42 Can I set an Angular directive template to a HTML web page? directive.templateUrl = "/templates/footer.html";
43 Explain $q service, deferred and promises? Promises are POST PROCESSING LOGICS which you want to execute after some operation / action is completed.  Below is the angular code for the above 4 steps.
// Step 1
    function SomeClass($scope,$q) {
// Step 2 
        var defer = $q.defer();
// step 3
        var promise = defer.promise;
// step 4
promise.then(function () {
            alert("Logic1 success");
        }, function () {
            alert("Logic 1 failure");
        });

promise.then(function () {
            alert("Logic 2 success");
        }, function () {
            alert("Logic 2 failure");
        });

    }
44 What are the filters  Filters are used to modify the data and clubbed in expression or directives using a pipe character
- currency
- date
- filter
- json
- limitTo
- lowercase
- number
- orderBy
- uppercase
{{ x | currency}}
45 Custom filter Creating our own custom filter myApp.filter("toText", function()
{
 return function(value)
 {
  if(value==1){
   return "One";
  }
  else if(value==2){
   return "Two";
  }
  else {
   return "Unknown";
  }
 }
});
46 Module and controller AngularJS module is nothing but a container of all angular components like controller, services, directive, filter, config etc

Controller is a JavaScript constructor function which controls the data
module
var myApp = angular.module(‘myModuleApp’,[]);

Controller
myApp.controller(‘myController’, function($scope) 

 
}); 
47 Explain ng-app directive to implement automatic angular bootstrap
48 What are compile & link options in Custom Directives Compile
It traverses the DOM and collects all of the directives and deals with transforming the template DOM. The result is a linking function.

Link
The link function deals with linking scope to the DOM
49 What is AngularJS BootStrap Process Automatic BootStrap
Manual BootStrap
50 scopeless controller var app = angular.module("myApp"); 
app.controller("myController", function()  

    this.title = 'scopeless Controller Test'; 
    this.name = 'Anupam'; 
    this.sayHello = function()  
    { 
        alert('Hello ' + this.name); 
    } 
}); 
51 Broadcast, Emit and On Broadcast: We can pass the value from parent to child
         i.e parent -> child controller.
Emit: we can pass the value from child to parent
         i.e.child ->parent controller.
On: catch the event dispatched by $broadcast or $emit.
52 How to stop the propagation Emit : StopPropagation
BroadCast : defaultPrevented -> this approach is more logical
event.stopPropagation();

event.defaultPrevented = true; 
then logic 
53 Jquery with Angular If we working with jquery then we have to keep 2 things
1. Jquery goes and manipulate HTML DOM, it has no affect on Angular DOM
2. To work you have to update scope object and kick off the digest cycle
$scope.$apply()
54 Jasmine  Jasmine is open source javascript framework  for unit testing
55 Where to check the result SpecRunner.html describe("", function(){
   it("Must return sum of 2 integer", function(){
          expect(Add(5,6).toBe(11);
    }
}

No comments:

Post a Comment