AngularJS Interview Questions – Set 05

Explain $rootScope in AngularJS.

Every AngularJS application contains a $rootScope, which is the top-most scope created on the DOM element. An application can contain only one $rootScope, which will be shared among all its components. Every other scope is considered as its child scope. It can watch expressions and propagate events. By using the root scope, one can set the value in one controller and read it from the other controller.

Describe MVC in reference to angular.

AngularJS is based on MVC framework, where MVC stands for Model-View-Controller. MVCperforms the following operations:

  • A model is the lowest level of the pattern responsible for maintaining data.
  • A controller is responsible for a view that contains the logic to manipulate that data. It is basically a software code which is used for taking control of the interactions between the Model and View.
  • A view is the HTML which is responsible for displaying the data.
    For example, a $scope can be defined as a model, whereas the functions written in angular controller modifies the $scope and HTML displays the value of scope variable.

What are the controllers in AngularJS?

Controllers are JavaScript functions which are used to provide data and logic to HTML UI. It acts as an interface between Server and HTML UI. Each controller accepts $scope as a parameter which refers to the application/module that controller is going to control. For example:

var app = angular.module(‘myApp’, []);
app.controller(‘myCtrl’, function($scope) {
$scope.firstName = “Aryan”;
$scope.lastName = “Khanna”;
});

Explain custom filters with an example.

We can create our own filters in AngularJS. It can be performed by associating the filter to our module. These types of filters are known as custom filters.

An example given below can be used to count the number of elements in the string by using the filter:

angular.module(‘myCountFilterApp’, [])
.filter(‘count’,function()
{
return(function(input)
{
var out=[];
out=input.split(‘,’);
return out.length;
})
});
As per above example, if the string is “21, 34, 45” then output after applying filter will be 3.