100 likes | 122 Views
Best Angular JS Training Institute: Angular JS Training Course offered by Visualpath Training Institute through best industry expert faculty. Enroll Now for free DEMO Class. For more details contact us@9704455959.
E N D
BEST ANGULARJS INTERVIEW QUESTION AND ANSWER Angular JS is the framework of choice for multiple high-end web applications. The reason many teams choose this technology is because it is flexible and powerful, seems to evolve in the right direction, has a great community, and has countless extensions and integrations. There are also many Angular developers. While starting out with Angular is fun and building small single page applications is not very difficult, maintaining even a small app can be tough. Until today, a large number of good practices and advanced techniques have been documented and discussed, and some high- quality standards have emerged. Working with Scopes Scopes are the data-model of Angular apps. They are the single source of truth in the app, and should be bound and handled with the greatest caution. There are many caveats in dealing with scopes. We will describe a few significant ones below. Q: How does scope inheritance work in AngularJS? Describe the various ways for data to be passed into a scope. Scope inheritance in AngularJS is prototypal for child scopes, but not for isolated scopes. Core directives, which create a new scope, use the child scope option. Those scopes have access to the models set on the parent scope. Accessing parent scope models works seamlessly for objects, but when trying to write to a primitive model (e.g. a string), a new model will be created on the child scope. The model on parent scope will be masked, or shadowed. When building custom directives, it is possible to create an isolated scope. Isolated scopes don’t have direct access to their parent’s models. Still, bindings can be set manually by specifying them in the directive’s scope property object. In such a case, data can be passed into the directive through HTML attributes. That supports both two-way and one-way bindings, and also expression bindings. Directives also have the ability to transclude scope onto contained elements. When using transclusion manually, it is possible to create a cloned scope – one that would keep all the properties of the parents, but would lose all the bindings. That feature is not very well documented. https://www.visualpath.in
At this point, it seems very important to note that it is possible to traverse scopes, in all directions. Every scope has a $parent property (“null” for root scope), and also childTail, nextSibling properties. It is possible to communicate between scopes using those properties, though it may be difficult and also not a good practice. Q: What exactly are controllers? What is their lifecycle and relation to the scope? 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. Even though at first controllers may seem like the primary ground of operation in AngularJS, once the developer truly understands the purpose of scopes in AngularJS, their use of controllers will minify. It is not optimal to perform calculations directly on scope models, as those might be watched, and in effect may trigger and slow down the digest phase. The motto that transcends MVC frameworks —“keep controllers thin” — applies very well to AngularJS. Controllers are bound to their scope, and so is their lifecycle. Once a new scope is created, the $compile service sets up initial watches on the scope. At that point, the scope can be manipulated, models on the scope can be created, mutated or destroyed, new watches and listeners can be set. For the changes to take effect, a digest phase needs to be triggered. That allows for observing and responding to model mutation (which is a reaction, thus the next step). The scope’s lifecycle ends with its destruction. Additional events are fired on that occasion. This usually is also the end of the interest for the controller, though it may live on as JavaScript closures do. Q: Please explain what “.$eval()” and “$parse()” are used for in AngularJS. “.$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. A good helper question to this one would be: did you, the developer, ever wonder why core Angular directives take only the model name set on the scope? E.g.: ‘Sets the value of scope model foo to 5`. In the directive, the scope object is implicit. What really happens: the expression passed to ng-click is parsed, which returns a function, which is then executed with the current scope passed in as context. 1 2 3 4 or shorter: $scope.foo = 3; var parseFn = $parse(‘foo = 5’); parseFn($scope); $scope.foo; // returns 5 https://www.visualpath.in
1 2 3 There are many use cases for $parse, as it is a really great service. A particularly useful one is to check for deep nested properties of objects when there is no assurance that at any level the property is not null. $scope.foo = 3; $scope.$eval(‘foo = 5’); $scope.foo; // returns 5 1 … will return undefined if foo.bar is undefined. If one would try to access “quux” directly, JavaScript would throw an exception. $parse(‘bar.baz.quux’)(foo); Another more specific use case is to allow users to declare variables and assign values to them, such as in text input fields, and then reuse the variables in other input fields (and more). An example of that might be a calculator or notepad application. To keep it safe, scope could be used as the context for the variables. “.$eval()” and “$parse()” would play key roles there. Working with the Digest Loop The digest loop is used to keep the DOM in sync with the models set on the scope. In Angular, running into issues around the digest cycle is common. A deep understanding of the digest cycle is much less common. The developer being interviewed should be familiar with what the digest cycle is and how it works. The requirement for that knowledge will emerge sooner than later when building a large application. The questions below will help you assess their level of proficiency. Q: How does AngularJS know when to perform dirty checking and update DOM output? The answer is short — when it is told to do so. The point is, there is no polling mechanism that would trigger dirty checking automatically. Core AngularJS directives, services, and methods usually set up watches, or fire the digest cycle explicitly. That process is executed internally, it is not exposed, and may not be obvious to the developers. In fact, there are articles which contradict the facts, falsely stating that there is a constant heartbeat in AngularJS. There is no such thing. Manipulating scope models using non-core functionality requires the developers to manually trigger the digest cycle. In most cases, that is done by using the scope method “.$apply()”, which triggers a digest on the root scope. That phase propagates down to every child scope. Without anything triggering digest, the dirty checking will not happen. The callbacks to watches will not be fired, and DOM output will not be updated. Q: What is the difference between “.$apply()” and “.$applyAsync()”? Why would you choose one over the other? 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 https://www.visualpath.in
“.$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()”. At this point, the reason should be obvious — the main concern is performance. Applying a certain change to your scope, only to redo or change it again in a fraction of a second can often be redundant. $applyAsync() helps avoid that. Q: What is the difference between “.$digest()” and “.$apply()”? Why would you ever call “.$digest()” on a scope? 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. Again, the reason why a developer might want to call “.$digest()” instead of “.$apply()” is performance. It can be safely done when working with isolated components, e.g. widgets, that don’t communicate with the rest of the app. More precisely — when it is known that no models set on parent scopes will be affected. However, it is not a common practice. As a rule of thumb, the use of “.$apply()” is preferred and expected. Services Services in Angular are where the business logic is kept. Even in core Angular, there is more than one (even more than two) supported ways of creating services. The style guides have a lot to say about optimal approaches in dealing with services. The engineer you consider hiring should too! Ranging from correctly applying patterns, through communication, persistent models, to handling client- side data stores, the services in Angular usually consist of advanced, complex methods that should be reusable across the application. The business logic itself requires proficiency in JavaScript. Binding it to Angular demands from the developer to comprehend what types of structures he or she intend to use. Q: Please explain when to use a service, when to use a factory, and when to use a provider. 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. https://www.visualpath.in
For Angular JS Online Training 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”. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Q: What are services in Angular JS? When are they initialized? function api() { this._apiUrl = ''; this.$get = function () { var that = this; var hostObject = { printApiUrl: function () { return ‘api address is ' + that._apiUrl; } }; return hostObject; }; } angular.module(‘myApp’) .provider(‘api’, api); angular.module(‘myApp’) .config(function (apiProvider) { apiProvider._apiUrl = ‘http://a-great-api.com'; }) .controller(’NewCtrl’, function ($scope, api) { $scope.apiName = api.printApiUrl(); }); 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). Providers become available prior to that, as they can be readily used in “config()” blocks. Their core functionality is still unavailable at that time. It can be manipulated though. Q: What means of HTTP communication are available in Angular JS? Describe and explain the differences between at least two. 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. https://www.visualpath.in
“$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. There is a common ground for both “$http” and “$resource” —the “$httpInterceptors”. More about those in the next section. A third alternative is Restangular. Restangular is a contributed module, and was built as a substitute for $resolve. It has a different, rich API, operates primarily on promises, and is supposed to have an easier syntax. In fact, developers consider $resource to be somewhat confusing. Restangular allows you to generate new types of requests on the fly. It is a fairly popular module. On the other hand, there haven’t been many commits lately. Miscellaneous AngularJS has a lot of power. To be able to use it, the developer often needs to dig in to documentations, techniques described on blogs and forums, and also into the source code. After spending some time building client-side applications using AngularJS, the engineers broaden their view on AngularJS. New paths open up as a result of searching for optimal approaches. A veteran developer should be at least somewhat familiar with the cases described in the questions and answers below. They all relate to advanced aspects of using Angular. The developer’s fluency in discussing them may indicate to you their thorough understanding of the framework. Q: What is transclusion, in relation to directives? Are there ways to manually control transclusion? Transclusion is a property of directives, which allows them to contain and access elements, which are declared within them in HTML hierarchy, but which are not declared in their templates. An example of that would be a lightweight directive, which when applied to an element creates a new scope for it, applied also to all contained elements. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 <div> PARENT SCOPE: foo: {{ foo }} <!-- assuming foo === 1 --> bar: {{ bar.hotNumber }} <!-- assuming bar.hotNumber === 1 --> <div light-scope> CHILD SCOPE https://www.visualpath.in
15 16 17 18 19 20 21 22 this can be a view template —notice that the content of the “div” to which the directive “light-scope” is bound is not part of the directive’s template. foo: {{ foo }} bar: {{ bar.hotNumber }} <button ng-click="foo = 2">change foo</button> <button ng-click="bar.hotNumber = 3">change bar.hotNumber</button></div> </div> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 function lightScope() { function postLink(scope, element, attrs, controller, transclude) { // allow to set isolated scope, // but not by default var isolateScope = false; if (attrs.lightScope === 'isolated') { isolateScope = true; } // there are two scopes: // one created by the directive in the definition, through `scope: true`, and // another one created just above... var newChildScope = scope.$parent.$new(isolateScope); transclude(newChildScope, function (clone) { element.append(clone); }); // ... so the second scope needs to be destroyed manually. scope.$on('$destroy', function () { newChildScope.$destroy(); }); } var directive = { link: postLink, restrict: 'E', scope: true, transclude: true }; return directive; } angular.module('lightScope', []) https://www.visualpath.in
40 So obviously, the “transclude()” function is very interesting. We provide it an arbitrary scope, and can append it to the DOM element. That will propagate to the elements below in the HTML hierarchy. .directive('lightScope', lightScope); Please refer to the official documentations for $compile service, they’re quite exceptional: Q: Is it possible to manipulate HTTP requests globally in AngularJS? Describe your approach. 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. Requests can be intercepted at: request (just before sending), request error, response success, and response error. Considering that also “$resource” relies on “$http” to cover XHRs and the functions passed to the $httpProvider.interceptors array, can be normal Angular factories, using interceptors is a good practice for general global manipulation of HTTP requests. Q: How does root scope differ from all other scopes? “$rootScopeProvider” is a service. It is a singleton; it does not have a parent, siblings, or another root. It was created directly from the “Scope()” class, and not through the “.$new” method of another scope. Perhaps the biggest differences are in how root scope is meant to be used. It’s primary use for developers is meant to be event handling. In Angular, “.$broadcast()” and “.$emit()” are ways to trigger events, which are sent down or up the scope hierarchy respectively. The effects are optimal at the root scope, i.e. “$rootScope.$emit()” will only be caught by listeners set on root scope, while “$rootScope.$broadcast()” will reach to all listeners in the app. Models should not be set on root scope. That scope can be seen as a form of global namespace, especially when evaluating expressions in the context of scopes. Polluting the global namespace is almost never a good practice. The recommendation in Angular documentations is to use root scope only for small parts of data, which are useful throughout the app (globals), but not functions. Testing Building applications without writing tests is a no-go. Fortunately, Angular was built with testability in mind. Writing tests requires developers to learn and apply different approaches, depending on what type of Angular structure is tested. Some of the differences may be subtle and incomprehensible without knowing the good practices of software development. Others may include alternative approaches to achieve the same goal. Setting up testing also for a continuous integration environment is the Angular developer’s responsibility. Who else would take care of it otherwise? Though the techniques described here are not required to build great applications, most of the teams behind the great applications value them deeply. https://www.visualpath.in
Q: Unit testing controllers and services – what are the differences? 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. For Angular JS Online Training Q: Please describe an approach to testing directives. Directives are responsible for handling new and/or complex functionalities within custom HTML tags. Directives are set through HTML, and in most cases their effects directly affect the user interface of an application. That is unlike services, whose effects usually have an indirect effect on the UI. Many directives have all of their logic in their postLink function. That function is not added to modules as controllers, services, and filters are, so they cannot be injected. Unless they are made globally available, it is very difficult reach them directly when testing. The recommended, official way to test directives using unit tests is to inject the “$compile” service, pass it a single HTML element with the directive set on it, and compile it against a scope, e.g. root scope. After that, a digest phase is manually called, and then the compiled HTML element is tested for expected results. 1 2 3 4 5 6 7 That approach is rather fast. It might just be a bit difficult to test directive’s reactions for complex user actions. This is where Protractor comes into play. Protractor is a testing framework for AngularJS, written on top of webdriver, which executes tests against Selenium servers. It is used for e2e testing. it('Should compile to expected results', function() { var element = $compile(' <div widget-component></div> ')($rootScope); $rootScope.$digest(); expect(element.html()).toContain('Simple as that'); }); https://www.visualpath.in
The alternative approach to testing directives is to do almost exactly the same thing, just with e2e tests. Compiling a directive in a unit test is a great way to isolate the directive. What is ultimately tested though is usually the visible HTML result. This alternative approach is about writing simple HTML pages, which load the directive (and it’s dependencies), and isolate the directive and its functionality on a simple page. No routing, nothing – just the directive. Such an HTML page is not yet the test — it is a standard example. The test needs to be run against that example page. This approach is particularly useful when writing libraries. The latter approach is a bit slower in terms of execution. The application needs to boot in order to test the directive. However, such a test has a lot of value. Even more value comes from the fact that in the process, an example HTML page is created — a very useful artifact. Perhaps such tests could be called functional tests, and not yet full e2e tests, because the developer should still want to isolate behaviour and add every module that the final application is using, to the example HTML page. Q: How would you automate the testing within a larger team, or in a production environment? This is not a strictly AngularJS question, but a veteran front-end developer should at least have an idea of how continuous integration environments work, in regard to front-end testing. First of all, we need to make the assumption that the project is version controlled with Git, and is hosted on GitHub, or BitBucket, or some similar code repository service. It would be great if at this point, the developer would mention gitflow, as it is a method with proven effectiveness. More importantly though, the developer should mention hooks, e.g. GitHub webhooks. Those are event handlers, described in-depth in a recent article on Toptal Blog, which allows HTTP requests to be made to arbitrary URLs in response to various repository events. An example would be to ping a third-party testing service when someone pushes commits to a repository. There are multiple services, most notable of which are Travis, another GitHub product, available for free for open source projects, and SauceLabs, which allow automated testing on mobile devices. Those tools will do most of the configuration automatically, including configuring the webhooks. What the front-end developer will need to provide is a script, most often a bash script, similar to what probably already is in the repository’s README.md file — the client application needs to be installed and run on the machine provided by the third-party testing service. The script usually installs all dependencies, runs the tests, builds the application, then deploys it. That last step is critical. The continuous environment, after successfully completing the tests, should perhaps push the code to a remote server. The author never used such processes to push to production, but he did set up several systems where deployment was performed automatically to pre-production servers, e.g. development and staging. In fact, those servers were never pushed manually again. Such setup relieves developers from having to do the build themselves — the only thing they need to do now is commit their code and push. Even more importantly — it runs the tests on another machine. The developer would be expected to test their changes locally anyway. If the tests pass both locally and remotely, there is a big chance that the code base is stable. I Hope this is very helpful for you. If you want to know more information about Angular JS Training or other IT related course then feel free to contact us at +91-9704455959 / 9618245689 https://www.visualpath.in