AngularJS Interview Questions and Answers

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

The first point of difference is that ng-ifit is created in the back when the expression is true of the dom node, ng-showis initially created, and use display:blockand display:noneto control the display and non-display.
The second difference is that ng-ifit will (implicitly) generate a new scope, ng-switchand ng-includeso will create a dynamic interface as well.
This will lead, in the ng-ifbinding with the basic variables ng-model, and to bind the outer div this model to another display region, when the inner changes, the outer layer will not change the synchronization, this time is because of the two variables.
<p>{{name}}</p>
<div ng-if="true">
    <input type="text" ng-model="name">
</div>
ng-show This problem does not exist because it does not come with a level.
The way to avoid this problem is to always bind the elements in the page to the object's property (data.x) rather than directly to the base variable (x).

Ng-repeat iteration array, if the array has the same value, what will be the problem, how to solve?

You will be prompted to Duplicates in a repeater are not allowed.add track by $indexresolve. Of course, you can also trace by any ordinary value, as long as you can uniquely identify each of the items in the array (to establish the association between the dom and the data).

What is the mechanism of the data binding? Detail the principle

Dirty check mechanism.
Bidirectional data binding is one of the core mechanisms of AngularJS. When the view of any data changes, will be updated to the model, when the model changes in the data, view will be synchronized update, obviously, this requires a monitor.
The principle is that Angular sets a listening queue on the scope model to listen for data changes and update the view. When each bound to a thing to view AngularJS will $watchqueue an inserted $watch, used for detecting whether there is a change in the model of what it monitors. When the browser receives an event that can be handled by the angular context, the $digestloop triggers, traverses all, $watchand finally updates dom.
Give a chestnut
<button ng-click="val=val+1">increase 1</button>
click will produce an update of the operating time (at least two trigger $digestcycle)
  • Push the button
  • The browser receives an event and goes into the angular context
  • $digestCycle is started, each query $watchwhether change
  • Since the monitoring $scope.val the $watchreport has changed, and therefore forced to perform another $digestcycle
  • The new $digestcycle is not detected change
  • The browser $scoperetrieves the controller , updating the .val new value corresponding to the dom
$digest The upper limit of the loop is 10 times (more than 10 times after throwing an exception to prevent infinite loop).

Two flat interface blocks a and b, if a trigger an event, which way to let b know? Detail the principle

This question is another way of saying how to communicate between flat interface modules. There are two ways, one is to share the service, one is based on the event.
Sharing service
In Angular, through the factory can generate a single object, in the need to communicate the module a and b can be injected into the object.
Based on events
This is divided into two ways
The first is by means of the parent controller. In the sub-controller to the parent controller to trigger ( $emit) an event, and then in the parent controller to monitor ( $on) events, and then $broadcastbroadcast ) to the child controller, so that through the incident to carry the parameters, the data through the parent controller, To spread.
The second is with the help $rootScopeEach Angular application has a root scope by default $rootScope, and the root scope is at the top level, and it is dropped from all levels. Therefore, if the sub-controller directly $rootScopebroadcasting and receiving event, the communication can be achieved between peers.

How should an angular application be well layered?

Directory structure
For small projects, you can organize them by file type, for example:
css
js
  controllers
  models
  services
  filters
templates  
But for larger projects, it is best to divide by business module, such as:
css
modules
  account
    controllers
    models
    services
    filters
    templates
  disk
    controllers
    models
    services
    filters
    templates
Modules under the best there is a common directory to store public things.
The split of the logic code
As an MVVM framework, the Angular application itself should be divided by model, view model (controller), view.
Here the logic of the code split, mainly as far as possible so that the controller layer is very thin. (Such as background data request, data sharing and caching, event-based inter-module communication, etc.), extract the common interface operation to the directive (such as the date selection, paging and other components into the package, etc.) , Extract the common formatting operation to the filter and so on.
In complex applications, you can also create a corresponding constructor for the entity, such as the hard disk (Disk) module, there may be a list, new, details of such a few views, and corresponding to the controller, then you can build a Disk constructor, Which to complete the data additions and deletions to check and verify the operation, there are related Disk with the Disk, into the Disk constructor and generate an instance, this example will have a delete and delete check and verify the method. This is both structured and multiplexed (making the controller layer thinner).

What are the differences between the commonly used routing libraries?

Angular1.x commonly used ngRoute and ui.router, there is a design for the Angular2 new router ( component- oriented). The latter is not used in the actual project, do not speak.
Both ngRoute and ui.router, as additional additional functionality of the framework, must be introduced in module dependencies.
the difference
NgRoute module is Angular own routing module, and ui.router module is based on ngRoute module development of third-party modules.
Ui.router is based on state (state), ngRoute is based on the url, ui.router module has a more powerful function, mainly in the view of the nesting.
Routing can be defined using ui.router clear parent-child relationship, and the stencil is inserted into the parent sub-route by routing template ui-view command <div ui-view></div>to go to the nested implement the view. But not so defined ngRoute, if you use both father and son in the view <div ng-view></div>will be caught in an endless loop.
Example
NgRoute
var app = angular.module('ngRouteApp', ['ngRoute']);
app.config(function($routeProvider){
    $routeProvider
        .when('/main', {
            templateUrl: "main.html",
            controller: 'MainCtrl'
        })
        .otherwise({ redirectTo: '/tabs' });
Ui.router
var app = angular.module("uiRouteApp", ["ui.router"]);
app.config(function($urlRouterProvider, $stateProvider){
    $urlRouterProvider.otherwise("/index");
    $stateProvider
        .state("Main", {
            url: "/main",
            templateUrl: "main.html",
            controller: 'MainCtrl'
        })

What are the challenges that can be encountered if you plan a full-component system with an aggressive directive?

Do not have their own directive done a full set of components, can not tell.
What you can think of is how the component interacts with the outside world and how it can be used with a simple configuration.

Belong to different teams to develop the application of the angular, if you want to do integration, which may encounter problems, how to solve?

You may encounter conflicts between different modules.
Such as a team all the development in moduleA under the other team to develop the code in the moduleB
angular.module('myApp.moduleA', [])
    .factory('serviceA', function(){
        ...
    })
    
angular.module('myApp.moduleB', [])
    .factory('serviceA', function(){
        ...
    })    
    
angular.module('myApp', ['myApp.moduleA', 'myApp.moduleB'])    
Will lead to two modules below the serviceA occurred coverage.
Seemingly in Angular1.x and there is no good solution, so it is best in the early unified planning, make a good agreement, in strict accordance with the agreed development, each developer only write a specific block code.

What are the shortcomings of the

Strong constraint
Resulting in higher learning costs, unfriendly to the front end.
But when compliance with AngularJS conventions, productivity will be high and friendly to Java programmers.
Not conducive to SEO
Because all the content is dynamically acquired and rendered, the search engine can not crawl.
One solution is for the normal user's access, the server responds to the contents of the AngularJS application; for the search engine's access, the response is specific to the SEO HTML page.
Performance issues
As an MVVM framework, because of the two-way binding of data, for large arrays, complex objects will have performance problems.
  1. Reduce monitoring items (such as unidirectional binding for data that does not change)
  2. Active set the index (specified track by, simple type default with its own when the index, the object default use $$hashKey, such as changed to track by item.id)
  3. Reduce the amount of rendering data (such as paging, or take a small amount of data each time, according to need to take)
  4. Data is flattened (for example, for a tree structure, a flat structure is used to construct a map and tree data. For tree operations, the tree data changes are synchronized to the original flat data due to the same reference to the flat data)
In addition, for Angular1.x, there are problems with dirty checks and module mechanisms.
Mobile end

Details of the "dependency injection"

chestnut
Dependency injection is a software design pattern that is designed to handle dependencies between code and reduce coupling between components.
Give up a chestnut, if you do not use AngularJS, want to query the data from the background and display in the front, you may need to do so:
var animalBox = document.querySelector('.animal-box');

var httpRequest = {
    get: function(url, callback){
        console.log(url + ' requested');
        var animals = ['cat', 'dog', 'rabbit'];
        callback(animals);
    }
}

var render = function(el, http){
    http.get('/api/animals', function(animals){
        el.innerHTML = animals;
    })
}

render(httpRequest, animalBox);
However, if you do not pass the parameters in the call render, as the following will be given, because not el and http (defined when dependent on the run time will not automatically find dependencies)
render();
// TypeError: Cannot read property 'get' of undefined
And the use of AngularJS, can be directly so
function myCtrl = ($scope, $http){
    $http.get('/api/animals').success(function(data){
        $scope.animals = data;
    })
}
In other words, when Angular App is running, call myCtrl, automatically made $scopeand $httptwo dependency injection.
principle
AngularJS dependent service name is inferred by the constructor parameter names through toString()to find the function corresponding to this definition of the character string, and then with n parameters which are parsed (dependencies), again dependent on the mapping to the corresponding take-dependent , After instantiation.
Previous
Next Post »

1 comments:

Click here for comments
padmini
admin
10 October 2018 at 00:56 ×

Nice and good article.Thanks for sharing this useful information. If you want to learn Angular js course online, please visit below site.
Angularjs online training
Angularjs online course
Angularjs online training in Hyderabad
Angularjs online course in kurnool
Angularjs online training in kurnool

Congrats bro padmini you got PERTAMAX...! hehehehe...
Reply
avatar

Popular Posts