Frequently asked: Angular JS Interview Questions and Answers — Part 02

Q1. What are all the properties in Directive Definition Object?

Some of them are,

restrict - Restrict an element to one of the four types 'EAMC'.

replace - Boolean value. If true the directive element (such as, <my-directive>) will be replaced with the template elements.

template - A string or a function that returns a string, that could be compiled into HTML elements. This template will be attached to the DOM.

templateUrl - A url in string or a function that returns the url. It will be fetched by the Angular compiler and will be attached to DOM.

controller - A controller name or a function. When set to a string, the name of the string is used to look up a controller registered elsewhere in our application

controllerAs - The controllerAs option enables us to set a controller alias, thus allowing us to publish our controller under this name.

require - The name of the controllers we need for the directive. This option is used to inject the controller of the required directives.

transclude - Transclude allows us to pass in an entire template, including its scope, to a directive. If we have any content inside our own directive, by default it will not be compiled and added by Angular. We need to set transclude to true, so that the contents are parsed and a function will be passed to the link function.

Q2. What is link and compile in directives? What are they used for?

link - The link function has control over the live data-bound DOM. It is used for adding event listeners, data manipulation and watching for data changes. It is invoked after the compile. The link function has three default parameters. If we require another directive controller, that controller function will be passed as the fourth parameter. And if we set transclude to true, then the transclude function will be passed as the fifth parameter. we can use this to take a clone of the transcluded DOM element, compile it, and insert it.

compile - The compile function runs before the directive template are attached to the DOM and before scope is linked to DOM. So we can not do any data binding. Thus, we can only do DOM transformations that are safe to do to within the compile function.

We cannot declare both link and compile functions. If compile is set, then it must return the link function. If the directive has the link then it will be ignored.

Finally, the compile function deals with transforming the template DOM. The link function deals with linking scope to the DOM.

Q3. What is scope in directive?

The scope in directives could have three values:

false - Default. In this case, Angular does not create a separate scope for the directive and it will have the controller scope in which it has declared.

true - a new scope object is created that prototypically inherits from its parent scope.

an Object {} - creates an isolated scope.

Q4. What is isolated scope in Angular? What is the use of it?

The isolated scopes are stand-alone, separate objects that do not inherit from its prototype hierarchy. However, we can bind properties on our isolated scope with the outside world.

In the HTML,

The output will be,

Assigning an object to the scope property makes the directive's scope to isolate. And we binding a property called title to the directive scope. We are telling to Angular to bind the value of the attribute called title to the scope property title. Now it will be accessible in our directive scope.

If the scope property and the attribute name is different we need mention that like, title: '@attrTitle'. Here title means the scope property and attrTitlemeans the HTML attribute attr-title in which the directive is attached. Isolated scope is used to create reusable components without affecting global scope.

Q5. What are all the bindings available in directive scope?

One way binding — mentioned as '@'. Binding in this way, the parent scope will not be notified if the value changes in the directive and vice versa.

Two way binding — mentioned as '='. Any changes in the directive scope property will be updated to the parent property and reverse is also same.

Method binding — mentioned as '&'. If we want to pass a function (or method) to the directive it should be mentioned as &.

Another one way binding — mentioned as '<'. Any changes in the parent scope will be affected in the directive scope. But the changes in directive scope will not reflect in parent. It is added from 1.5.x version of Angular.

Q6. What is dirty checking in Angular JS? Or, how Angular checks data change and update it?

Angular defines a concept of a so called digest cycle which is also called dirty checking. This cycle can be considered as a loop, during any changes in the $scope.

Whenever we bind something in the view, Angular adds it to the watchers. When some changes happened in the view or model, Angular triggers the $digest cycle which is loop through the watchers array. It then compares the previous and new value of all the watchers. If any value is changed, then it triggers the watchers function which then updates the view or model.

We can also manually add a scope variable to the watchers array by using $watch.

Q7. What is $apply and $digest?

$digest is used to trigger the digest cycle in angular. It is used to loop through the watchers array and detect any scope changes. Angular automatically calls the $digestcycle whenever changes happen inside the Angular world.

Sometimes, we need to change the scope variables outside the Angular world. That time Angular does not aware of the changes and would not trigger the $digest cycle for us. For example, setTimeout or XMLHTTPRespone. To do that, we can manually trigger $apply which in turns trigger the $digest for us. It optionally accetps a function which will run the function in try...catch black and trigger the $digest. By using $apply, we will check the watchers in all the scope.

Q8. Why do we use $timeout and $interval in Angular instead of default functions?

If we use setTimeout and setInterval, Angular does not aware of the scope changes and will not trigger the $digest cycle for us. Thus any changes in the $scopewill not be reflected.

By using $timeout and $interval, we are wrapping our functions and run in inside Angular context. So thus, Angular automatically runs the $digest cycle automatically.

Q9. What is $http service in Angular?

$http service is one of the Angular's core services used to communicate with the HTTP servers. This service is based on the deferred/promise API exposed by the $q service.

The then functions will be once the request is resolved by either success or error.

Q10. What is emit and broadcast in Angular? When to use that?

AngularJS provides $on, $emit, and $broadcast services for event-based communication between controllers.

$emit dispatches an event upwards through the scope hierarchy and notify to the registered listeners. The event life cycle start with the scope on which the event dispatched and travel through the upward scope till $rootScope reached or one of the scope stop propagating. If we emit an event in $rootScope, then only the $rootScopecan listen the event since there are not scope in the upward hierarchy.

$broadcast dispatches an event downwards to all the child scopes and notify to the registered listeners. This event can not be cancelled.

$on is used to listen to the event by its name and receives the message.

Q11. What are all the ways available to communicate between AngularJS controllers and modules?

Following is the ways AngularJS provides to communicate between controllers and modules:

1. Using $rootScope. Since the $rootScope is at the top of the hierarchy chain, adding a property in $rootScope will be available in all the controllers. But since $rootScope is more like global scope, it is best to avoid adding many properties in $rootScope.

2. Using services. Add the data or functions to the services and inject them where we want to use them.

3. $emit and $broadcast. A publisher-subscriber pattern in AngularJS to register event listeners and dispatch events to share data.

Q12. What is Dependency Injection or DI?

Dependency Injection is an application design pattern that deals how a component can get hold of its dependencies.

For example consider a function which is needed in many components across our application. To use them, we need to pass them somehow, or re-create the same function inside the component. But in Angular, we don’t have this headache. Angular uses $inject service which will automatically fetch the services we want and pass them to our components. All we need is just simply declare the dependency we are going to use and pass them inside our function.

Angular has five types of injectables, which are service, factory, provider, value, and constant.

Q13. What is decorator in AngularJS?

decorator is used to when we want to tweak some minor changes in a service that our module depends. Because, we don't want to change the service.

In order to decorate a service, we need to inject the $delegate, which is the original service instance that we can decorate.

Q14. How do you create custom validation in AngularJS?

To create a custom validation rule for an input field, we can simply create a directive and define our validation function and add it in the $parsers array.

Consider an input field, where we want the user to input a number from 1 to 10, we can create the custom function as shown below:

We need the ngModelController to set the validity. And the $parsers array contains the list of validations and we add our own validation rule at the start of the array. When the condition is true, we set the validity of oneToTen rule to true otherwise false.

Q15. What is routing? And how Angular handle the routing?

In a single-page app, navigating from one page view to another is very important. In Angular routing, based on the URL, we are loading a template inside the ng-viewdirective.

Using the $routeProvider, we can take advantage of the browser's history navigation and enable users to bookmark and share specific pages, as it uses the current URL location in the browser.

The routing funcionalities in Angular are available in a separate module called ngRoute. First we need to install the angular-route.js, then add the ngRoute module as a dependency.

For more angular JS Interview questions with answer visit my blog: http://blog.vigowebs.com/post/2017/angularjs-interview-questions/