We Have Just Revamped Our Website!

We Have Just Revamped Our Website!
Welcome to our new revamped website. We were working very hard from last couple of weeks to get this major redesign implemented. And here we are today with new fast, attractive, responsive and easy to navigate design.

The old design was okay but it was little behind the time. It just didn't have features and support for modern day users and browsers. So it was the right time for us to revamp this website and provide a better user experience. We have completely revamped our design and improved site navigation. The aim was to get modern look, as well as make it easy to navigate. We hope we have delivered on this.

We would love to hear from you about this new look. Please provide your feedback in comment section.

Note: We have couple of new features in our plate and we will be releasing them soon. Keep watching!!!!

Define multiple Angular apps in one page

Recently in my previous post, I have posted about Different ways of bootstrapping AngularJS app, where you can either auto-bootstrap using ng-app attribute or manually bootstrap using angular.bootstrap function. And also mentioned in angular interview questions that "Only one AngularJS application can be auto-bootstrapped per HTML document." Which means that your page can only have single ng-app attribute. If you put multiple ng-app attribute, only first will be considered and the rest will be ignored.


You may also like:
Let's see with an example. In the below code, there are 2 ng-app present on the page.
<div ng-app="firstApp">
  <div ng-controller="FirstController">
    <p>1: {{ desc }}</p>
  </div>
</div>

<div ng-app="secondApp">
  <div ng-controller="SecondController">
    <p>2: {{ desc }}</p>
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
<script type="text/javascript">
var firstApp = angular.module('firstApp', []);
firstApp.controller('FirstController', function($scope) {
    $scope.desc = "First app.";
});

var secondApp = angular.module('secondApp', []);
secondApp.controller('SecondController', function($scope) {
    $scope.desc = "Second app.";
});
</script>
And below is the output. Out of 2 ng-app present on the page, the first one gets initialized and works as expected. Output also shows the same.
1: First app.
2: {{ desc }}

Then how can you define 2 different angular apps on the same page? Well, there are a couple of ways to implement this.

Manually bootstrapping each app

You can manually bootstrap both the application using angular.bootstrap() as we have seen in Different ways of bootstrapping AngularJS app.
var firstApp = angular.module('firstApp', []);
firstApp.controller('FirstController', function($scope) {
   $scope.desc = "First app. ";
});

var secondApp = angular.module('secondApp', []);
secondApp.controller('SecondController', function($scope) {
  $scope.desc = "Second app. ";
});

var dvFirst = document.getElementById('dvFirst');
var dvSecond = document.getElementById('dvSecond');

angular.element(document).ready(function() {
   angular.bootstrap(dvFirst, ['firstApp']);
   angular.bootstrap(dvSecond, ['secondApp']);
});
Since we are bootstrapping them manually, make sure to remove ng-app attribute from the HTML page.

Manually bootstrapping second app

You can also manually bootstrap the second app, where the first app gets initialized via ng-app
var firstApp = angular.module('firstApp', []);
firstApp.controller('FirstController', function($scope) {
   $scope.desc = "First app. ";
});

var secondApp = angular.module('secondApp', []);
secondApp.controller('SecondController', function($scope) {
  $scope.desc = "Second app. ";
});

var dvSecond = document.getElementById('dvSecond');

angular.element(document).ready(function() {
   angular.bootstrap(dvSecond, ['secondApp']);
});
So make sure that there is ng-app present on the page for first app.

Using dependency injection to inject both in root app

You can define a root level app using ng-app and then inject both the apps as module in root app.
var rootApp = angular.module('rootApp', ['firstApp','secondApp']);
var firstApp = angular.module('firstApp', []);
firstApp.controller('FirstController', function($scope) {
   $scope.desc = "First app. ";
});

var secondApp = angular.module('secondApp', []);
secondApp.controller('SecondController', function($scope) {
  $scope.desc = "Second app. ";
});
And make sure any parent node (body/Parent div) is assigned with ng-app=rootApp".

Hope you find this useful!!!!!

Use console.group for better JavaScript debugging

For debugging JavaScript/jQuery code, the easiest and preferred way is to use console.log() to output a message in web console. But it works fine when you have small amount of logging message. But having large number of logging makes log messy and unreadable.

console.group() can be used to group related log messages and use console.groupEnd()to close the group. Like,
console.group("Func 1 start");
console.log("Loop start.");
console.log("i:" + i);
console.log("Loop end.");
console.groupEnd();
And below is the output in console window. The log message are displayed within a group.
Console Group Message

You may also like:
This is quite useful when you are debugging multiple functions at same time and then using console.group() you can easily group them function wise.

Another nice feature is that you can also nest groups which allows to output message in hierarchical manner.
console.group("Func 1 start");
console.log("Loop start.");

//Nested Group
console.group("In Loop");
console.log("i:" + i);
console.groupEnd();

console.log("Loop end.");
console.groupEnd();
And below is the output in console window.
If you see the output, all the groups created as open by default. console.groupCollapsed() allows you to create collapsed group by default. The user will need to use the disclosure button next to it to expand it, revealing the entries created in the group. And call console.groupEnd() to back out to the parent group.
console.groupCollapsed("Func 1 start");
console.log("Loop start.");
console.log("i:" + i);
console.log("Loop end.");
console.groupEnd();
Few things to note.
  • Its not compulsory to pass group name in console.group() and console.groupCollapsed() but you should pass the group name to find out what message are being grouped together.
  • Don't pass group name to console.groupEnd() because it will always close the most recently created logging group.

Hope you find this useful. Happy debugging!!!!!

Latest AngularJS interview questions - Part 4

With continuation of AngularJS interview question series, after Part-1, Part-2 and Part-3, here is list of 4th set of 10 AngularJS interview questions and their answers.
Latest AngularJS interview questions - Part 1
Latest AngularJS interview questions - Part 2
Latest AngularJS interview questions - Part 3


Q31. What is ng-bind directive and how to use it?
Ans: ng-bind directive is used for displaying any model property value. It is same as {{ expression }}. But it is advisable to use ng-bind over expression. The reason is, when AngularJS is not loaded (for any reason), then ng-bind directive will not be visible. But in case of expression, whatever you have put within double curly brackets will be displayed in plain text.
<div ng-controller="MyController">
  <h1>My website address is <span ng-bind="website"></span></h1>
</div>

Q32. What is ng-model directive and how to use it?
Ans: ng-model directive is used to bind model's property to any input control like textbox, dropdown etc. It binds the view into the model.
<div ng-controller="MyController"> 
  Enter any text : <input type="text" name="search" ng-model="search" />
  <h2>You have searched for <span ng-bind="search"></span> !</h2> 
</div>
And your model has a property named "search".
var myApp = angular.module('myApp', []);
    myApp.controller('MyController', ['$scope',
      function($scope) {
        $scope.search = 'nothing';
      }
    ]);

And if the property doesn't exist on the scope, it will be created implicitly and added to the scope. But then what's the difference between ng-model and ng-bind?. Well, ng-bind directive is used only for display purpose or one way data binding Model -> View, where ng-model can be used for two way data binding Model -> View and View -> Model. Like in above example, when you change input type text, it is updating the model as well.


Q33. What is ng-controller directive and how to use it?
Ans: ng-controller directive is used to attach controller to view. You must have seen use of this directive in previous examples. Go to Part-3 to read more about ng-controller.

Q34. What is ng-repeat directive and how to use it?
Ans: ng-repeat directive is just like for-each loop in C#. Its like you iterate through a parent collection and process every child element. ng-repeat directive does exactly the same. Consider, you have following data and you want to display this in bulleted list.
$scope.users = [
    {name: 'John',age: 25}, 
    {name: 'Adams', age: 29}, 
    {name: 'Chris', age: 31}, 
    {name: 'Eric', age: 19}, 
    {name: 'Jon', age: 29}, 
    {name: 'Ronald', age: 27}, 
    {name: 'Ben', age: 37}, 
    {name: 'Joe', age: 26}, 
    {name: 'Henry', age: 22}, 
    {name: 'Linda', age: 16}, 
];
And in your view,
<ul>
   <li ng-repeat="user in users">
     {{user.name}} - {{user.age}} years.
   </li>
</ul>

Q35. What are filters and how to use it?
Ans: Filters in Angular allows to select a subset of items using expression. Filters can be added to expressions and directives using a pipe character. Suppose we want to sort the names (previous question demo) and display the result, then we can use "orderBy" filter.
<ul>
   <li ng-repeat="user in users | orderBy:'name' ">
      {{user.name}} - {{user.age}} years.
   </li>
</ul>
Another filter is "limitTo"
<ul>
   <li ng-repeat="user in users | limitTo:5 ">
      {{user.name}} - {{user.age}} years.
   </li>
</ul>
And you can also use filters with expression. For example, if you want to display name in uppercase then
<ul>
   <li ng-repeat="user in users ">
      {{user.name | uppercase}} - {{user.age}} years.
   </li>
</ul>
Below are list of filters supported by Angular.
  • filter: Selects a subset of items from array and returns it as a new array.
  • currency: Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default symbol for current locale is used.
  • number: Formats a number as text.
  • date: Formats date to a string based on the requested format.
  • json: Allows you to convert a JavaScript object into JSON string.
  • lowercase: Converts string to lowercase.
  • uppercase: Converts string to uppercase.
  • limitTo: Creates a new array or string containing only a specified number of elements. The elements are taken from either the beginning or the end of the source array, string or number, as specified by the value and sign (positive or negative) of limit.
  • orderBy: Orders a specified array by the expression predicate. It is ordered alphabetically for strings and numerically for numbers.

Q36. What is ngShow and ngHide directives and how to use it?
Ans: ng-show and ng-hide directive allow to show or hide elements based on expression value. This is quite useful as you don't have to do showing or hiding yourselves with CSS or JavaScript.
<div ng-hide="true">I'm hidden.</div>
<div ng-show="true">I'm shown.</div>
Or you can pass model values in expression.
<div ng-show="prop1"></div>
So when $scope.prop1 is truthy (element is visible).
var myApp = angular.module('myApp', []); 
myApp.controller('MyController', ['$scope',
   function($scope) {
     $scope.prop1 = true;
     $scope.prop2 = false;
   }
]);
You can also pass function() as expression which returns true or false.
<div ng-hide="IsInputCorrect()"></div>

Q37. What is ng-click and ng-change directive and how to use it?
Ans: The best part about AngularJS directives are that they are self explanatory. Just looking at the name, one can imagine what should be use of the directive. ng-click directive allows you to specify custom behavior when an element is clicked. And ng-change directive is used to find out when any value gets changed for input, select control.

Q38. What is ng-submit directive and how to use it?
Ans: ng-submit directive is used to submit the form. But it only works when your form doesn't contain any action attribute. You can pass a function name to ng-submit and when form is submitted, the function will get called.
<form ng-submit="submit()" ng-controller="SubmitController">

Q39. What is Module in AngularJS and what is angular.module?
Ans: "Module" in AngularJS is like container which can be used to contain different part of your application like controller, services, directives etc. Creating modules not only helps separating the code into individual concerns but makes them reusable and also improves unit-testability. Module can work independently and they can be dependent on other modules.Using angular.module, we can create module in AngularJS.
angular.module(‘module-name’,[dependencies]);
Every module should have a unique name, which is specified in the first parameter. Second parameter is an array, which may contain names of other dependent modules or services. If the module is not dependent then array should be left blank.
// Creating module with no dependency
var myModule = angular.module('myModule', []); 
//OR Creating module with dependency on other modules 
angular.module('myApp', ['dependency1', 'dependency2']);

Q40. What is Data binding in AngularJS and how it works?
Ans: Data binding in generic term is "a process that establishes a connection between the application UI and business logic." Same is true in case of Angular. Data-binding in Angular apps is the automatic synchronization of data between the model and view components. There are two types of bindings.

One Way - One way data binding is when model values are assigned to the HTML elements using data binding syntax like expression or ng-bind directive. But the change in HTML elements don't change the values in the model. So its one-way. We have already seen demo using ng-bind directive (Q31).

Two Way - In simple terms two-way data binding is when the model changes, the view reflects the change, and vice versa. Two-way bindings in AngularJS are created with the ng-model directive. Practically, two-way bindings can be applied only to those elements that allow the user to provide a data value, which means the input, textarea, and select elements. We have already seen demo using ng-model directive (Q32).

That completes Part-4. If you have not read Part 1, Part 2 and Part 3 then do read and keep visiting for upcoming set of interview questions and answers. You can also subscribe to RSS feed, follow us on Facebook and twitter to get the updates about this blog.

You can also Download jQuery Interview Questions free eBook.

Latest AngularJS interview questions - Part 3

With continuation of AngularJS interview question series, after Part 1 and Part 2, here is list of 3rd set of 10 AngularJS interview questions and their answers.

Latest AngularJS interview questions - Part 1
Latest AngularJS interview questions - Part 2
Latest AngularJS interview questions - Part 4


Q21. What is Angular Expression?
Ans: Angular expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. For example, these are valid expressions in Angular:
  • {{ 3+4 }}
  • {{ a+b }}
  • {{ user.name }}
  • {{ items[index] }}


Q22. How Angular expressions are different from JavaScript expressions?
Ans: Angular expressions are like JavaScript expressions but there are few differences.
  • Context : In Angular, the expressions are evaluated against a scope object, while the JavaScript expressions are evaluated against the global window object.
  • Forgiving: In Angular expression evaluation is forgiving to null and undefined, while in JavaScript undefined properties generates TypeError or ReferenceError.
  • No Control Flow Statements: Loops, conditionals or exceptions cannot be used in an Angular expression.
  • No Comma And Void Operators: You cannot use , (comma) or void in an Angular expression. And You cannot create regular expressions in an Angular expression.

Q23. What is compilation process in Angular?
Ans: Once you have the markup, the AngularJS needs to attach the functionality. This process is called "compilation" in Angular. Compiling includes rendering of markup, replacing directives, attaching events to directives and creating a scope. The AngularJS has compiler service which traverses the DOM looking for attributes. The compilation process happens in two phases.
  • Compilation : traverse the DOM and collect all of the directives and creation of the linking function.
  • Linking: combine the directives with a scope and produce a live view. The linking function allows for the attaching of events and handling of scope. Any changes in the scope model are reflected in the view, and any user interactions with the view are reflected in the scope model.
When you create a new directive, you can write compile and/or linking functions for it to attach your custom behavior.

To understand the compilation process of Angular, must read "The nitty-gritty of compile and link functions inside AngularJS directives".


Q24. What is scope in AngularJS?
Ans: A scope is an object that ties a view (a DOM element) to the controller. In the MVC framework, scope object is your model. In other words, it is just a JavaScript object, which is used for communication between controller and view.

Q25. What is $rootscope in AngularJS?
Ans: The $rootScope is the top-most scope. An app can have only one $rootScope which will be shared among all the components of an app. Hence it acts like a global variable. All other $scopes are children of the $rootScope. Since $rootScope is a global, which means that anything you add here, automatically becomes available in $scope in all controller. To add something in $rootScope, you need to use app.run function which ensures that it will run prior to the rest of the app. You may say that "run" function is like "main" method of angular app.
app.run(function($rootScope) {
  $rootScope.name = "AngularJS";
});
And then you can use in your view. (via expression)
<body ng-app="myApp">
  <h1>Hello {{ name }}!</h1>
</body>

Q26. What are controllers in AngularJS?
Ans: In Angular, a Controller is a JavaScript constructor function. When a Controller is attached to the DOM via the ng-controller directive, Angular will instantiate a new Controller object, using the specified Controller's constructor function. The job of a controller is to pass data from the model, to the view or the view can asks for something from the controller, and the controller turns to the model and takes that thing, and hands it back to the view.
var myApp = angular.module('myApp', []);
myApp.controller('MyController', ['$scope', function($scope) {
    $scope.website = 'jquerybyexample.net';
  }
]);
And then in your HTML using ng-controller directive,
<div ng-controller="MyController">
  <h1>My website address is {{ website }}!</h1>
</div>

Q27. What is the difference between $scope and scope in AngularJS?
Ans: $scope is used while defining a controller (see previous question) where scope is used while creating a link function for custom directive. The common part is that they both refers to scope object in AngularJS, but the difference is that $scope uses dependency injection where scope doesn't. When the arguments are passed-in via dependency injection, their position doesn't matter. So for example, a controller defined as ($scope as first parameter)
myApp.controller('MyController', ['$scope', function($scope, $http) {
OR ($scope is second parameter)
myApp.controller('MyController', ['$scope', function($http, $scope) {
In both the case, the postion of $scope doesn't matter to AngularJS. Because AngularJS uses the argument name to get something out of the dependency-injection container and later use it.

But in case of link function, the position of scope does matter because it doesn't uses DI. The very first parameter has to be scope and that's what AngularJS expects.
app.directive("myDirective", function() {
  return {
    scope: {};
    link: function(scope, element, attrs) {
      // code goes here.
    }
  };
});
However you can name it anything of your choice. In below code, foo is your scope object.
link: function(foo, bar, baz) {
  // code goes here.
}

Q28. What is MVC Architecture in AngularJS?
Ans: In AngularJS, scope objects are treated as Model. The View is display of model that is your data. And the model gets initialized within a JavaScript constructor function, called Controller in AngularJS. Let take a look at below code to understand it better.
<!DOCTYPE html>
<html>

<head>
  <script data-require="angular.js@*" data-semver="1.3.6" src="https://code.angularjs.org/1.3.6/angular.js"></script>
  <link rel="stylesheet" href="style.css" />
  <script>
    var myApp = angular.module('myApp', []);
    myApp.controller('MyController', ['$scope',
      function($scope) {
        $scope.website = 'jquerybyexample.net';
      }
    ]);
  </script>
</head>

<body ng-app="myApp">
  <div ng-controller="MyController">
    <h1>My website address is {{ website }}</h1>;
  </div>
</body>
</html>
Here MyController is a Controller and $scope (Model) is populated within Controller. And later on in div element $scope object data is displayed (View).


Q29. Can we have nested controllers in AngularJS?
Ans: YES. We can create nested controllers in AngularJS. Nested controller are defined in hierarchical manner while using in View. Take a look at below code. Here the hierarchy is "MainCtrl -> SubCtrl -> SubCtrl1".
<div ng-controller="MainCtrl">
  <p>{{message}} {{name}}!</p>

  <div ng-controller="SubCtrl">
    <p>Hello {{name}}!</p>

    <div ng-controller="SubCtrl2">
      <p>{{message}} {{name}}! Your username is  {{username}}.</p>
    </div>
  </div>
</div>

Q30. In case of nested controllers, does the $scope object shared across all controllers?
Ans: YES. The $scope object is shared across all controllers and it happens due to scope inheritance. Since the ng-controller directive creates a new child scope, we get a hierarchy of scopes that inherit from each other. So if we define a property on a parent scope, the child scope can manipulate the property. And if the property is not present in child scope, then parent scope property's value is used. Lets consider, the previous question HTML where there are 3 controllers. And here is the AngularJS code to define these controllers.
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope',
  function($scope) {
    $scope.message = 'Welcome';
    $scope.name = 'Jon';
  }
]);
myApp.controller('SubCtrl', ['$scope',
  function($scope) {
    $scope.name = 'Adams';
  }
]);
myApp.controller('SubCtrl2', ['$scope',
  function($scope) {
    $scope.name = 'Ema';
    $scope.username = 'ema123';
  }
]);
You will see that the controller "SubCtrl2" doesn't have "message" property define but it is used in HTML. So in this case, the immediate parent scope property will be used. But immediate parent scope which is "SubCtrl" in this case, also doesn't have "message" property. So it again goes one level up and finds the property is present so it uses parent scope value for "message" property and displays it.


That completes Part-3 as well. If you have not read Part 1 and Part 2 then do read and keep visiting for upcoming set of interview questions and answers. You can also subscribe to RSS feed, follow us on Facebook and twitter to get the updates about this blog.

Also read,
Latest AngularJS interview questions - Part 1
Latest AngularJS interview questions - Part 2
Latest AngularJS interview questions - Part 4

You can also Download jQuery Interview Questions free eBook.