AngularJS interview questions and angularjs questions

Source: Internet
Author: User
Tags emit

AngularJS interview questions and angularjs questions

What are the differences between ng-if and ng-show/hide?

The first difference is that ng-if creates this dom node only when the following expression is true. ng-show is created at the initial time and uses display: block and display: none.

The second difference is that ng-if will generate a new scope (implicitly), and ng-switch and ng-include will dynamically create an interface.

This will cause the ng-model to be bound with the basic variable in ng-if, and the model is bound to another display area in the outer div. When the inner layer changes, the outer layer does not change synchronously, because at this time, there are already two variables.

<p>{{name}}</p><div ng-if="true">  <input type="text" ng-model="name"></div>

Ng-show does not have this problem because it does not have a level-1 Scope.

To avoid such problems, you can always bind the elements on the page to the Property (data. x) of the object instead of directly binding it to the basic variable (x.

For details, see the scope in AngularJS.

When ng-repeat iterates an array, if the array has the same value, what is the problem? How can this problem be solved?

The system will prompt Duplicates in a repeater are not allowed. You can solve the problem by adding track by $ index. Of course, you can also trace by any common value, as long as you can uniquely identify each item in the array (establish the association between dom and data ).

Can I use methods on JS native objects for expressions written in ng-click?

Not only ng-click expressions, but native JS methods cannot be directly called as long as they are on the page, because they do not exist in the $ scope of the Controller corresponding to the page.

Example:

<P >{{ parseInt (55.66) }}< p>

You will find that nothing is displayed.

However, if you add this function to $ scope:

$scope.parseInt = function(x){  return parseInt(x);}

In this way, there is no problem.

For this requirement, using a filter may be a good choice:

<p>{{13.14 | parseIntFilter}}</p>app.filter('parseIntFilter', function(){  return function(item){    return parseInt(item);  }})

In the expressions {now | 'yyyy-MM-dd'}, which of the following parameters can be customized?

Filter, format the data, receive an input, process according to a rule, and return the processing result.

Built-in filter

Ng has nine built-in filters:

Date)

Currency (currency)

LimitTo (limit the length of an array or string)

OrderBy)

Lowercase (lower case)

Uppercase (uppercase)

Number (format the number, add the thousands separator, and receive the parameter to limit the number of decimal places)

Filter (process an array and filter out elements containing a substring)

Json (format A json object)

Filter can be used in either of the following ways:

<P >{{ now | date: 'yyyy-MM-dd' }}</p>

Another method is to use in js:

// $ Filter ('filter name') (object to be filtered, parameter 1, parameter 2 ,...)
$ Filter ('date') (now, 'yyyy-MM-dd hh: mm: ss ');

Custom filter

// Form app. filter ('filter name', function () {return function (object to be filtered, filter parameter 1, filter parameter 2 ,...) {//... objects after return processing;}); // chestnut app. filter ('timesfilter', function () {return function (item, times) {var result = ''; for (var I = 0; I <times; I ++) {result + = item;} return result ;}})

What is the relationship between factory, service, and provider?

Factory

Put service methods and data in an object and return this object

app.factory('FooService', function(){  return {    target: 'factory',    sayHello: function(){      return 'hello ' + this.target;    }  }});

Service

Creates a service by using the constructor and returns an instantiated object.

app.service('FooService', function(){  var self = this;  this.target = 'service';  this.sayHello = function(){    return 'hello ' + self.target;  }});

Provider

Create a service that can be configured through config. The content returned by $ get is the content of the service created using factory.

App. provider ('fooservice', function () {this. configData = 'init data'; this. setConfigData = function (data) {if (data) {this. configData = data ;}} this. $ get = function () {var self = this; return {target: 'provider', sayHello: function () {return self. configData + 'hello' + this.tar get ;}}}); // FooService providerapp is injected here. config (function (FooServiceProvider) {FooServiceProvider. setConfigData ('config data ');});

At the underlying implementation level, the service calls factory and returns its instance; the factory calls provider and returns the content defined in $ get. The factory and service functions are similar, except that factory is a common function and can return anything (return can be accessed, so how to write private variables, you know); service is the constructor, no return is allowed (all bound to this can be accessed); provider is an enhanced factory and a configurable factory is returned.

For details, see Factory vs Service vs Provider in AngularJS.

What mechanism does angular use for data binding? Detailed Principles

Dirty check mechanism.

Bidirectional data binding is one of the core mechanisms of AngularJS. When any data changes in the view, it is updated to the model. When the data in the model changes, the view is also updated synchronously. Obviously, this requires monitoring.

Angular sets a listening queue on the scope model to listen for data changes and Update views. AngularJS inserts a $ watch into the $ watch queue every time it binds something to the view to check whether there is any change in the model it monitors. When the browser receives an event that can be processed by angular context, the $ digest loop is triggered to traverse all $ watches and update the dom.

Example

<Button ng-click = "val = val + 1"> increase 1 </button>

Click generates an update operation (at least two $ digest cycles are triggered)

Press the button

The browser receives an event and enters angular context

$ Digest starts to execute the loop and queries whether each $ watch changes.

Because $ watch of $ scope. val monitors changes, force another $ digest loop.

No changes are detected in the new $ digest loop.

The browser retrieves the controller and updates the dom corresponding to $ scope. val.

$ Digest the maximum number of loops is 10 (an exception is thrown after 10 loops are exceeded to prevent infinite loops ).

For details, see AngularJS data binding.

Two levels of interface blocks a and B. If an event is triggered in a, what methods can B know? Detailed Principles

This is another way of saying: how to communicate between hierarchical interface modules. There are two methods: sharing services and event-based.

Shared Service

In Angular, you can use factory to generate a singleton object, and inject this object into modules a and B that require communication.

Event-based

There are two ways to do this:

The first is to use the parent controller. Trigger an event ($ emit) to the parent controller in the sub-controller, listen to the ($ on) event in the parent controller, and broadcast ($ broadcast) to the sub-controller, in this way, data is transmitted between controllers at the same level through the parameters carried by the event through the parent controller.

Second, use $ rootScope. Each Angular application has a root scope $ rootScope by default. The root scope is located at the top level, and all levels of scopes are hung down from it. Therefore, if the Sub-controller directly uses $ rootScope to broadcast and receive events, it can implement communication between the same level.

For details, see communication between controllers in AngularJS.

How Should an angular application be well layered?

Directory structure division

Small projects can be organized by file type, for example:

cssjs controllers models services filterstemplates 

However, for large projects, it is best to divide them by business modules, for example:

cssmodules account  controllers  models  services  filters  templates disk  controllers  models  services  filters  templates

It is better to have a common directory under modules to store public things.

Split logic code

As an MVVM framework, Angular applications should be divided by models, view models (controllers), and views.

Here, the logic code splitting mainly refers to making the controller layer thin as much as possible. Extract the shared logic to the service (such as background data requests, data sharing and caching, and event-based Inter-module communication ), extract common interface operations to direve ve (for example, encapsulate the date selection and paging into components), and extract common formatting operations to the filter.

In complex applications, you can also create corresponding constructors for entities, such as the hard Disk module, which may have views such as list, creation, and details, and corresponding to the controller, you can create a Disk constructor to complete data addition, deletion, modification, query, and verification operations. There are Disk-related controllers, inject the Disk constructor and generate an instance. This instance has the addition, deletion, modification, query, and verification methods. In this way, the layers are distinct and reusable (making the controller layer thinner ).

Refer to AngularJS's in-depth practices in the Suning cloud center

Which routing libraries are commonly used by angular applications and what are their differences?

Angular1.x is commonly used in ngRoute and ui. router, and a new router (component-oriented) designed for Angular2 ). I will not talk about the one that has not been used in the actual project.

Both ngRoute and ui. router must be introduced as module dependencies as additional functions of the framework.

Differences

The ngRoute module is the routing module of Angular, And the ui. router module is a third-party module developed based on the ngRoute module.

Ui. router is based on state, and ngRoute is based on url. The ui. router module has more powerful functions, mainly reflected in the nesting of views.

Use the ui. the router can define a route with a clear parent-child relationship and insert the child path from the template to the <div ui-view> </div> of the parent routing template using the ui-view command, in this way, view Nesting is realized. NgRoute cannot be defined in this way. If <div ng-view> </div> is used in both parent and child views, it will be 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'    })

If angular direve VE is used to plan a fully componentized system, what challenges may it face?

I did not use directive to build a full set of components.

One thing you can think of is how components interact with the outside world, and how they can be used through simple configuration.

Angular applications developed by different teams. If integration is required, what problems may be encountered and how to solve them?

Conflicts may occur between different modules.

For example, all the development of one team is under moduleA, and the code developed by the other team is under moduleB.

angular.module('myApp.moduleA', [])  .factory('serviceA', function(){    ...  })  angular.module('myApp.moduleB', [])  .factory('serviceA', function(){    ...  })    angular.module('myApp', ['myApp.moduleA', 'myApp.moduleB'])  

It will overwrite serviceA under the two modules.

It seems that there is no good solution in Angular1.x, so it is best to make a unified planning in the early stage, make a good deal of agreement, develop in strict accordance with the Agreement, each developer only writes Specific block code.

What are the disadvantages of angular?

Strong Constraint

This results in high learning costs and unfriendly front-end.

But according to the AngularJS conventions, the productivity will be high, and it is friendly to Java programmers.

Not conducive to SEO

Because all content is dynamically obtained and rendered, the search engine cannot crawl it.

One solution is that the server responds to the content of AngularJS applications for access by normal users. For access by search engines, the server responds to HTML pages specifically for SEO.

Performance problems

As the MVVM framework, the two-way data binding is implemented, which may cause performance problems for large arrays and complex objects.

You can use this method to optimize the performance of Angular applications:

Reduce monitoring metrics (for example, one-way binding to unchanged data)

Actively set the index (specify the track by, which is used as the index by default for simple types, and $ hashKey for objects by default, for example, change to track by item. id)

Reduce the rendering data volume (such as paging, or fetch a small amount of data each time, and retrieve the data as needed)

Data flattening (for example, for a tree structure, a flat structure is used to construct a map and tree data. When operating on a tree, tree data changes are synchronized to the original flat data)

In addition, for Angular1.x, there are dirty checks and module mechanisms.

Mobile Terminal

You can try Ionic, but it is not perfect.

For more information, see what Peter-Paul Koch thinks about Angular in January 2015?

What is the controller as syntax introduced in angular 1.2?

Fundamental benefits

Before angular 1.2, any binding on the view was directly bound to $ scope.

function myCtrl($scope){  $scope.a = 'aaa';  $scope.foo = function(){    ...  }}

With controllerAs, you do not need to inject $ scope. controller becomes a very simple javascript Object (POJO), a more pure ViewModel.

Function myCtrl () {// capture this using vm to avoid the Context Change var vm = this when internal functions use this; vm. a = 'aaa ';}

Principle

From the implementation of the source code, the controllerAs syntax only creates an attribute for the instance of the controller object using the as alias on $ scope.

if (directive.controllerAs) {  locals.$scope[directive.controllerAs] = controllerInstance;}

However, in this way, in addition to making the controller more POJO, you can also avoid AngularJS scope-related pitfalls (that is, the above ng-if produces a level-1 Scope pit, in fact, it is also a pitfall for inheriting the median type in the javascript prototype chain. If controllerAs is used, all the fields in view are bound to a referenced property, such as vm. xx, so the pit no longer exists ).

<div ng-controller="TestCtrl as vm">  <p>{{name}}</p>  <div ng-if="vm.name">    <input type="text" ng-model="vm.name">  </div></div>

Problem

One problem encountered when using controllerAs is that $ scope is not injected, and the methods under $ scope, such as $ emit, $ broadcast, $ on, and $ watch, cannot be used. These event-related operations can be encapsulated for unified processing, or $ scope can be introduced into a single controller for special treatment.

See angular controller as syntax vs scope

Elaborate on angular's "dependency injection"

Chestnuts

Dependency injection is a software design pattern designed to process dependencies between codes and reduce coupling between components.

For example, if AngularJS is not used and you want to query data from the background and display the data on the front end, you may need to do this:

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 parameters when calling render, an error will be reported like the following, because el and http cannot be found (dependent upon the definition, does not automatically search for dependencies during running)

Render ();
// TypeError: Cannot read property 'get' of undefined

AngularJS can be used directly.

function myCtrl = ($scope, $http){  $http.get('/api/animals').success(function(data){    $scope.animals = data;  })}

That is to say, when the Angular App is running, call myCtrl to automatically inject $ scope and $ http dependencies.

Principle

AngularJS uses the parameter name of the constructor to infer the dependent service name, and uses toString () to find the string corresponding to the function defined by this function, then, use the regular expression to parse the parameters (dependencies), obtain the corresponding dependencies in the dependency ing, and input them after instantiation.

To simplify the process, it is probably like this:

Var inject = {// storage dependency ing: {}, // register the dependency register: function (name, resource) {this. storage [name] = resource;}, // parse the dependency and call resolve: function (target) {var self = this; var FN_ARGS =/^ function \ s * [^ \ (] * \ (\ s * ([^ \)] *) \)/m; var STRIP_COMMENTS = /((\/\/. * $) | (\/\ * [\ s \ S] *? \ * \/)/Mg; fnText = target. toString (). replace (STRIP_COMMENTS, ''); argDecl = fnText. match (FN_ARGS) [1]. split (/,? /G); var args = []; argDecl. forEach (function (arg) {if (self. storage [arg]) {args. push (self. storage [arg]) ;}}) return function () {target. apply ({}, args );}}}

Using this injector, you can call the aforementioned chestnuts without AngularJS.

inject.register('el', animalBox);inject.register('ajax', httpRequest);render = inject.resolve(render);render();

Problem

Because AngularJS injector assumes that the parameter name of the function is the name of the dependency, and then searches for the dependency, if the dependency is injected as in the preceding example, after the code is compressed (the parameter is renamed), the dependency cannot be found.

// Function myCtrl = ($ scope, $ http) {...} // function myCtrl = (a, B) {...} after compression ){...}

Therefore, the following two methods are usually used to inject dependencies (requirements are imposed on the order of dependency addition ).

Array Comment Method

myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){  ...}])

Explicit $ inject

myApp.controller('myCtrl', myCtrl);function myCtrl = ($scope, $http){  ...}myCtrl.$inject = ['$scope', '$http'];

Supplement

A di container must have three elements: registration of dependencies, declaration of dependencies, and object acquisition.

In AngularJS, both module and $ provide can provide registration of dependencies; built-in injector can get objects (automatically complete dependency injection); Dependency declaration, as mentioned above.

The following is a chestnut

// For a module, more than one passing parameter indicates creating a module, and an empty array indicates not relying on other modules. // there is only one parameter (module name), indicating obtaining the module // defining the myApp, add myApp. services is its dependency angular. module ('myapp', ['myapp. services ']); // define a service module and register all services under this module angular. module ('myapp. services ', []) // $ provider has factory, service, provider, value, constant // defines an HttpServiceangular. module ('myapp. services '). service ('httpservice', ['$ http', function ($ http) {...}])

Reference

[AngularJS] implements a simple dependency injection.

Understand the module and injector in angular, that is, dependency injection.

Actual application scenarios of dependency injection in AngularJS

Angular2

Compared with Angular1.x and Angular2, Angular2 is a completely new framework.

Based on TypeScript (TypeScript can be used for development), strong language type is more advantageous for large project team collaboration.

Componentized to improve development and maintenance efficiency.

Module supports dynamic loading, new router, promise native support, and so on.

It is worth looking forward to meeting future standards and absorbing the advantages of other frameworks, but there are more things to learn at the same time (ES next, TS, Rx, etc ).

The above is the preparation of AngularJS interview questions. We will continue to add relevant materials later. Thank you for your support for this site!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.