Angular English Flashcards

1
Q

List at least three ways to communicate between modules of your application using core AngularJS functionality.

A

Common ways to communicate between modules of your application using core AngularJS functionality include:

Using services
Using events
By assigning models on $rootScope
Directly between controllers, using $parent, \$\$childHead, \$\$nextSibling, etc.
Directly between controllers, using ControllerAs, or other forms of inheritance
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which means of communication between modules of your application are easily testable?

A

Using a service is definitely easy to test. Services are injected, and in a test either a real service can be used or it can be mocked.

Events can be tested. In unit testing controllers, they usually are instantiated. For testing events on $rootScope, it must be injected into the test.

Testing $rootScope against the existence of some arbitrary models is testable, but sharing data through $rootScope is not considered a good practice.

For testing direct communication between controllers, the expected results should probably be mocked. Otherwise, controllers would need to be manually instantiated to have the right context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

When a scope is terminated, two similar “destroy” events are fired. What are they used for, and why are there two?

A

The first one is an AngularJS event, “$destroy”, and the second one is a jqLite / jQuery event “$destroy”. The first one can be used by AngularJS scopes where they are accessible, such as in controllers or link functions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you reset a “$timeout”, and disable a “$watch()”?

A

The key to both is assigning the result of the function to a variable.

To cleanup the timeout, just “.cancel()” it:

var customTimeout = $timeout(function () {
  // arbitrary code
}, 55);

$timeout.cancel(customTimeout);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Name and describe the phases of a directive definition function execution, or describe how directives are instantiated.

A

The flow is as follows:

First, the “$compile()” function is executed which returns two link functions, preLink and postLink. That function is executed for every directive, starting from parent, then child, then grandchild.

Secondly, two functions are executed for every directive: the controller and the prelink function. The order of execution again starts with the parent element, then child, then grandchild, etc.

The last function postLink is executed in the inverse order. That is, it is first executed for grandchild, then child, then parent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How does interpolation, e.g. “{{ someModel }}”, actually work?

A

It relies on $interpolation, a service which is called by the compiler. It evaluates text and markup which may contain AngularJS expressions. For every interpolated expression, a “watch()” is set. $interpolation returns a function, which has a single argument, “context”. By calling that function and providing a scope as context, the expressions are “$parse()”d against that scope.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How does the digest phase work?

A

In a nutshell, on every digest cycle all scope models are compared against their previous values. That is dirty checking. If change is detected, the watches set on that model are fired. Then another digest cycle executes, and so on until all models are stable.

It is probably important to mention that there is no “.$digest()” polling. That means that every time it is being called deliberately. As long as core directives are used, we don’t need to worry, but when external code changes models the digest cycle needs to be called manually. Usually to do that, “.$apply()” or similar is used, and not “.$digest()” directly.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

List a few ways to improve performance in an AngularJS app.

A

The two officially recommended methods for production are disabling debug data and enabling strict DI mode.

The first one can be enabled through the $compileProvider:

myApp.config(function ($compileProvider) {
$compileProvider.debugInfoEnabled(false);
});

Using one-time binding where possible. Those bindings are set, e.g. in “{{ ::someModel }}” interpolations by prefixing the model with two colons. In such a case, no watch is set and the model is ignored during digest.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is $rootScope and how does it relate to $scope?

A

$rootScope is the parent object of all $scope Angular objects created in a web page.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What exactly are controllers? What is their lifecycle and relation to the scope?

A

Controllers are classes, that is, constructor functions, which are bound to a scope AND a section of HTML through the directive “ng-controller”, routing, or through a directive. Setting a controller creates a new scope (child scope). The controller’s purpose is to set up the initial state of the scope and also manipulate it by adding behaviour, setting watches, event listeners, etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Please explain what “.$eval()” and “$parse()” are used for in AngularJS.

A

“.$eval()” is a simple scope method which takes an expression (and optionally locals) and then executes it against the current scope, using “$parse()”.

The service “$parse()” is where the magic happens. It takes an Angular expression and returns a function, which takes two arguments: “context” and “locals”. The latter is used for overriding variables set in the context. The context is the key part.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is the difference between “.$apply()” and “.$applyAsync()”? Why would you choose one over the other?

A

The main difference between them is that the latter happens on a 0 timeout. The actual delay is about 10ms. Consecutive “.$applyAsync()” calls cancel the previous timeouts. The point is that for multiple “.$applyAsync()” calls, there will only be a single digest trigger, and not one for every call. That would be the case with the regular “.$apply()”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between “.$digest()” and “.$apply()”? Why would you ever call “.$digest()” on a scope?

A

There are a few differences. First of all, “.$apply()” takes an argument, an expression, and evaluates it against the current scope. “.$digest()” does not take any arguments.

Secondly, “.$apply()” calls “.$digest()” on root scope. That digest will propagate down through every child scope — it will eventually affect every scope in the application. Calling “.$digest()” directly on a scope does not affect any scope that is higher in the hierarchy. That means that any watches set on parent scopes will not be evaluated.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Please explain when to use a service, when to use a factory, and when to use a provider.

A

The three are almost the same internally. When initialized, a service returns a factory, which in turn returns a provider.
The difference between services and factories lies in how they are declared and initialized. Services are constructor functions — they are instantiated, that is, when first loaded a “new” instance is created. The consequence is that when declaring a service, all its methods are defined as properties of “this”. Factories, on the other hand, should return an object literal.

There is an advantage to knowingly using providers, as they can be configured before all services are available, in “config()” blocks. When declaring a provider named e.g. “api”, Angular registers two injectables: “api” and “apiProvider”.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are services in AngularJS? When are they initialized?

A

Angular services are singletons — there is only one instance available during an app’s lifecycle. Angular lazy loads its modules, so all services become available after they were injected into a “run()” block, or into another module (which of course needs to be initialized too).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What means of HTTP communication are available in AngularJS? Describe and explain the differences between at least two.

A

The two core services for Angular that deal with XHRs are “$http” and “$resource”. The latter actually needs explicit installation, while “$http” is readily available.

“$http” is a low level module, which already provides a lot of functionality, but using it with a RESTful API might lead to duplication of code, and is somewhat primitive. The module can be used for communicating using XML HTTP Requests or JSONP. It is rather simple to use.

“$resource”, on the other hand, is a high level service built on top of “$http”, designed for communicating with RESTful APIs. It was built to deal with standard server-side resources. It provides a rich api, allowing the declaration and reuse of multiple defined parameters, even ones which can be used alternatively on the same path level. It provides standard actions (except for “update”, but that one is described as an example in the module’s documentation). It also allows new actions to be defined.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Is it possible to manipulate HTTP requests globally in AngularJS? Describe your approach.

A

Yes, requests can be intercepted, and Angular provides a great api to do that - the “$http” interceptors. “.interceptors” is an array, available at “$httpProvider”, so it can be manipulated from “.config()” blocks. That array should consist of functions which return an object, basically factories.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Unit testing controllers and services - what are the differences?

A

The main difference between unit testing controllers and services stems from the differences in concerns. Controllers are used for setting the initial state and behavior of the scope they are bound to. We could say that all the models set on scope, either directly or using the //this// keyword, are public. This is still somewhat similar to the public properties of services. Controllers should not contain business logic though.

In unit testing controllers, one could expect more assurances of the initial values of models, and less logic. The logic in controller methods should mostly be just coupling UI actions to services. All functionality that is not tightly bound to the current view and scope, should be delegated to services. The developer would definitely have more spies set on mocked services objects in controller tests than in service tests.

Conversely, the services should be tested primarily for correct business logic handling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What should be the maximum number of concurrent “watches”? Bonus: How would you keep an eye on that number?

A

To reduce memory consumption and improve performance it is a good idea to limit the number of watches on a page to 2,000. A utility called ng-stats can help track your watch count and digest cycles.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How do you share data between controllers?

A

Create an AngularJS service that will hold the data and inject it inside of the controllers.

There are couple of other ways to implement data sharing between controllers, like:
– Using events
– Using $parent, nextSibling, controllerAs, etc. to directly access the controllers
– Using the $rootScope to add the data on (not a good practice)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What is the difference between ng-show/ng-hide and ng-if directives?

A

ng-show/ng-hide will always insert the DOM element, but will display/hide it based on the condition. ng-if will not insert the DOM element until the condition is not fulfilled.

ng-if is better when we needed the DOM to be loaded conditionally, as it will help load page bit faster compared to ng-show/ng-hide.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What is a digest cycle in AngularJS?

A

In each digest cycle Angular compares the old and the new version of the scope model values. The digest cycle is triggered automatically. We can also use $apply() if we want to trigger the digest cycle manually.

23
Q

Where should we implement the DOM manipulation in AngularJS?

A

In the directives. DOM Manipulations should not exist in controllers, services or anywhere else but in directives.

24
Q

Is it a good or bad practice to use AngularJS together with jQuery?

A

It is definitely a bad practice. We need to stay away from jQuery and try to realize the solution with an AngularJS approach. jQuery takes a traditional imperative approach to manipulating the DOM.

AngularJS, however, takes a declarative approach to DOM manipulation.

25
Q

How would you specify that a scope variable should have one-time binding only?

A

By using “::” in front of it. This allows the check if the candidate is aware of the available variable bindings in AngularJS.

26
Q

What is the difference between one-way binding and two-way binding?

A
  • One way binding implies that the scope variable in the html will be set to the first value its model is bound to (i.e. assigned to).
  • Two way binding implies that the scope variable will change it’s value everytime its model is assigned to a different value
27
Q

Explain how $scope.$apply() works

A

$scope.$apply re-evaluates all the declared ng-models and applies the change to any that have been altered (i.e. assigned to a new value) .

$scope.$apply() is one of the core angular functions that should never be used explicitly, it forces the angular engine to run on all the watched variables and all external variables and apply the changes on their values

28
Q

What directive would you use to hide elements from the HTML DOM by removing them from that DOM not changing their styling?

A

The ngIf Directive, when applied to an element, will remove that element from the DOM if it’s condition is false.

29
Q

What makes the angular.copy() method so powerful?

A

It creates a deep copy of the variable.

A deep copy of a variable means it doesn’t point to the same memory reference as that variable.

30
Q

How would you make an Angular service return a promise? Write a code snippet as an example

A

To add promise functionality to a service, we inject the “$q” dependency in the service, and then use it like so:

angular.factory('testService', function($q){
	return {
		getName: function(){
			var deferred = $q.defer();
			//API call here that returns data
			testAPI.getName().then(function(name){
				deferred.resolve(name)
			})
		return deferred.promise;
	}
} })
31
Q

What is the role of services in AngularJS and name any services made available by default?

A
  • AngularJS Services are objects that provide separation of concerns to an AngularJS app.
  • AngularJS Services can be created using a factory method or a service method.
  • Services are singleton components. All components of the application (into which the service is injected) will work with single instance of the service.
  • An AngularJS service allows developing of business logic without depending on the View logic which will work with it.

Few of the inbuilt services in AngularJS are:
– the $http service: The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP.

32
Q

When creating a directive, it can be used in several different ways in the view. Which ways for using a directive do you know? How do you define the way your directive will be used?

A

When you create a directive, it can be used as an attribute, element or class name. To define which way to use, you need to set the restrict option in your directive declaration.

The restrict option is typically set to:

‘A’ – only matches attribute name
‘E’ – only matches element name
‘C’ – only matches class name

33
Q

When should you use an attribute versus an element?

A

Use an element when you are creating a component that is in control of the template. Use an attribute when you are decorating an existing element with new functionality.

34
Q

How do you reset a $timeout, $interval(), and disable a $watch()?

A
To reset a timeout and/or $interval, assign the result of the function to a variable and then call the .cancel() function.
var customTimeout = $timeout(function () {
  // arbitrary code
}, 55);

$timeout.cancel(customTimeout);

to disable $watch(), we call its deregistration function. $watch() then returns a deregistration function that we store to a variable and that will be called for cleanup

var deregisterWatchFn = $scope.$on(‘$destroy’, function () {
    // we invoke that deregistration function, to disable the watch
    deregisterWatchFn();
});
35
Q

Explain what is a $scope in AngularJS

A

Scope is an object that refers to the application model. It is an execution context for expressions.
Scopes are objects that refer to the model. They act as glue between controller and view.

36
Q

What are Directives?

A

Directives are markers on a DOM element (such as an attribute, element name, comment or CSS class) that tell AngularJS’s HTML compiler ($compile) to attach a specified behavior to that DOM element.

37
Q

What is a singleton pattern and where we can find it in Angularjs?

A

Is a great pattern that restricts the use of a class more than once. We can find singleton pattern in angular in dependency injection and in the services.

38
Q

What is an interceptor? What are common uses of it?

A

An interceptor is a middleware code where all the $http requests go through.

The interceptor is a factory that are registered in $httpProvider. You have 2 types of requests that go through the interceptor, request and response.

39
Q

How would you programatically change or adapt the template of a directive before it is executed and transformed?

A

You would use the compile function. The compile function gives you access to the directive’s template before transclusion occurs and templates are transformed, so changes can safely be made to DOM elements.

40
Q

How would you validate a text input field for a twitter username, including the @ symbol?

A

You would use the ngPattern directive to perform a regex match that matches Twitter usernames.

41
Q

Explain what is string interpolation in Angular.js ?

A

In Angular.js the compiler during the compilation process matches text and attributes using interpolate service to see if they contains embedded expressions. As part of normal digest cycle these expressions are updated and registered as watches.

42
Q

Explain what is linking function and type of linking function?

A

Link combines the directives with a scope and produce a live view. For registering DOM listeners as well as updating the DOM, link function is responsible.

Post linking function: Post linking function is executed after the child elements are linked. It is safe to do DOM transformation by post-linking function

43
Q

Explain what is injector?

A

An injector is a service locator. It is used to retrieve object instances as defined by provider, instantiate types, invoke methods and load modules. There is a single injector per Angular application, it helps to look up an object instance by its name.

44
Q

Explain what is the difference between link and compile in Angular.js?

A
  • Compile function: It is used for template DOM Manipulation and collect all of the directives.
  • Link function: It is used for registering DOM listeners as well as instance DOM manipulation. It is executed once the template has been cloned.
45
Q

Explain what is factory method in AngularJS?

A

For creating the directive, factory method is used. It is invoked only once, when compiler matches the directive for the first time. By using $injector.invoke the factory method is invoked.

46
Q

Explain what is DI (Dependency Injection ) and how an object or function can get a hold of its dependencies ?

A

DI or Dependency Injection is a software design pattern that deals with how code gets hold of its dependencies. In order to retrieve elements of the application which is required to be configured when module gets loaded , the operation “config” uses dependency injection.

47
Q

How can you improve ng-repeat directives?

A

Using “track by” for example: ng-repeat=”task in $ctrl.tasks track by task.id”

48
Q

Do you use ng-include? Do you think it should used or avoided and why?

A

It should be avoided.

  • Has a significant performance hit on apps
  • Performs slower than completed components, scopes, etc.
  • Initialization takes longer
  • Replace usages with real components.
49
Q

Why do you consider it should be used ng-change instead of $watch?

A
  • Only triggers for changes made by the user.
  • Expresses intent more clearly.
  • Easier to trace.
  • More performance, saves on watches.
50
Q

What are some differences between Services and Factories?

A
  • Factories are functions that return the object.
  • Services are constructor functions of the object.
  • A common rule in the Angular community is that projects that use ES5 should go with factories.
  • Projects that make use of ES6 classes should use services since ES6 classes can be simply used as services in Angular without any change.
51
Q

What should $q.defer be used for?

A

Wrapping callbacks in promises

52
Q

Can you describe how it works the component lifecycle hooks?

A

$onInit: Angular automatically invokes this method after instantiating the controller.
$onDestroy: when a controller is discarded.
$onChanges: when input bindings change.
$postLink: where you can do low-level work directly against the DOM (Like a directive in previous versions).

53
Q

What is the main benefit of using Provider as a service provider?

A

The primary benefit of using the more low-level provider function is that is configurable during the module configuration phase.