Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

AngularJS Common Interview Questions and Answers


May 08, 2021 AngularJS



Angular is a very popular front-end framework and is loved by a wide range of front-end developers. B elow, w3cschool will list some classic Angle interview questions and answers for your reference.

AngularJS Common Interview Questions and Answers

Q1, what is the difference between ng-if and ng-show/hide?

A: There are two main differences:

1, ng-if creates the dom node when the later expression is true, and ng-show is created at the beginning, and display:block and display:none can be used to control the display and not display.

2, ng-if will (implicitly) produce new scopes, ng-switch, ng-include, etc. will dynamically create an interface as well.

This results in the ng-model being bound with a base variable in ng-if, and when a colleague binds the model to another display area in the div of the outer layer, the outer layer does not change with the inner layer as it changes, as there are already two different variables.

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

In ng-show, however, this problem does not exist because it does not come with a first-level scope.

To avoid such problems, we can always bind elements from the page to the properties of the object (data.x) instead of directly to the base variable (x).


Q2, ng-repeat iterative array, if the array has the same value, what will be the problem, how to solve?

A: Duplicates in a repeater are not allowed. W hen this happens, we can solve it by $index track by. Of course, you can trace by any ordinary value, as long as you can uniquely identify each item in the array (establish an association between dom and data).


Can expressions written in Q3 and ng-click use methods on JS native objects?

A: Not only in ng-click, but as long as it is on the page, native JS methods cannot be called directly because they do not exist in Controller's $scope corresponding to the page.

For example:

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

We'll find that nothing is shown.

However, $scope added the following function to the $scope:

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

It's natural that there's nothing wrong with running.

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

<p>{{13.14 | parseIntFilter}}</p>

app.filter('parseIntFilter', function(){
    return function(item){
        return parseInt(item);
    }
})


Q4、{{now | I n this expression, how can vertical lines and subsequent parameters be customized?

A: filter, format the data, receive an input, process it according to a rule, and return the processing results.


ng There are nine main types of filters built into it:

1:date (date)

2:currency (currency)

3: limitTo (limit array or string length)

4: OrderBy (sort)

5: lowercase (lowercase)

6: uppercase (capital)

7:number (format the number, plus thousands separator, and receive parameters to limit the number of points)

8:filter (process an array that filters out elements that contain a substring)

9: json (formatted json object)


There are two ways to use filters:

One is directly on the page:

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

The other is used in js:

// $filter('过滤器名称')(需要过滤的对象, 参数1, 参数2,...)
$filter('date')(now, 'yyyy-MM-dd hh:mm:ss');

Custom filter

// 形式
app.filter('过滤器名称',function(){
    return function(需要过滤的对象,过滤器参数1,过滤器参数2,...){
        //...做一些事情  
        return 处理后的对象;
    }
});  
// 栗子
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 Q5, factory, service, and provider?

factory

Put the service's methods and data in one object and return it.

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

service

Create the service as a constructor, and then return an instantiated object.

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

provider

To create a service that can be configured by config, $get returned in , is to create the contents of the service with 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.target;
      }
    }
  }
});
 
// 此处注入的是 FooService 的 provider
app.config(function(FooServiceProvider){
  FooServiceProvider.setConfigData('config data');
});

From the underlying implementation point of view, the relationship between the three is: service calls the factory, returns its instance, and factory calls the provider, returns what is defined in its $get. Factory is similar in functionality to service, but factory is a normal function that can return anything, service is a constructor that can not be returned (accessible to this) ;p rovider is an enhanced factory that returns a configurable factory.


Q6, angular data binding using what mechanism? D etail the principle

A: A dirty check mechanism is used.

Bidirectional data binding is one of the core mechanisms of AngularJS. W hen there is any data change in the view, it is updated to the model. I f the data in the model changes, the view is updated synchronously, which obviously requires a monitoring.

Principle

Angular sets up a listening queue on the scope model that can be used to monitor data changes and update the view. E ach time a thing is bound to the view, AngularJS inserts a $watch into the $watch queue to detect changes in the model it monitors. When the browser receives an event that can be handled by the angular context, the $digest loop fires, traverses all the $watch, and finally updates the dom.


Q7, two level interface blocks a and b, if an event is triggered in a, what are some ways to let b know? D etail the principle

A: The question is, to put it another way, how to communicate between level interface modules. T here are two approaches, one is a common service and the other is event-based.

Shared services

In Angular, a single object can be generated through factory, which can be injected into modules a and b that require communication.

Event-based

This is divided into two ways

The first is with the help of the parent controller. A n event ($emit) is triggered to the parent controller in the child controller, then the $on event is listened to in the parent controller, and then broadcast ($broadcast) to the child controller, so that the data passes through the parent controller and propagates between the parent controllers through the parameters carried by the event.

The second is with the help of $rootScope. E ach Angular app has a root scope $rootScope by default, with the root scope at the top and the levels of scope hanging from it down. Therefore, if the subcontroller $rootScope broadcast and receive events directly, communication between classes can be achieved.


Q8, how should an angular application be well layered?

The division of the directory structure

For small projects, you can organize by file type, such as:

css
js
 controllers
 models
 services
 filters
templates 

However, 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

It's best to have another common directory under modules to store public stuff.

The split of the logical code

As an MVVM framework, the Angular application itself should be divided by model, view model (controller), view.

The split of the logical code here is mainly to make the controller layer as thin as possible. E xtract common logic into service (e.g. requests for background data, data sharing and caching, event-based inter-module communication, etc.), extract common interface operations into directives (e.g., encapsulating date selection, page, etc. into components, etc.), extract common formatting operations into filters, and so on.

In complex applications, you can also establish corresponding constructors for entities, such as hard disk modules, there may be lists, new, details and other views, and corresponding to controller, then you can build a Disk constructor, which completes the data addition and correction and validation operations, there is a Disk-related controller, inject disk constructors and generate an instance, this example has an addition and error check and validation method. This is both hierarchical and multi-use (making the controller layer thinner).


Q9, angular applications commonly used which routing libraries, what are the differences?

A: ngRoute and ui.router are commonly used in Angular1.x.

Difference

The ngRoute module is the routing module that comes with Angular, while the ui.router module is a third-party module developed based on the ngRoute module.

ui.router is state-based, ngRoute is url-based, and the ui.router module has more powerful features, mainly in terms of view nesting.

Using ui.router, you can define routes that have a clear parent-child relationship and insert child routing templates into the parent routing template through the ui-view directive, which enables view nesting. T his cannot be defined in ngRoute, and if you use the same in the parent-child view, you will fall into a dead 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'
    })


Q10, angular applications developed by different teams, if you want to integrate, what problems may you encounter, how to solve them?

A: Conflicts between different modules may be encountered.

For example, one team develops all under moduleA and the other team develops code under moduleB

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

This causes the serviceA below the two modules to overwrite.

It seems that there is no good solution in Angular 1.x, so it is best to plan for unity in the early stages, do a good job of convention, develop in strict accordance with the convention, each developer only writes specific block code.


What are the disadvantages of Q11, angular?

Strong constraints

Leads to higher learning costs and unfriendly to the front end.

However, compliance with the conventions of AngularJS can be productive and Java-friendly.

Not good for SEO

Because everything is dynamically acquired and rendered, search engines cannot crawl.

One solution is that for normal user access, the server responds to the content of the AngularJS app, and for search engine access, to HTML pages specifically targeted at SEO.

Performance issues

As an MVVM framework, there are performance issues with large arrays and complex objects because of the two-way binding of data.

Ways to optimize the performance of your Angular application:

Reduce monitoring items (e.g. one-way binding of data that does not change)

Actively set the index (specify track by , the simple type uses itself as the index by default, the object uses $$hashKey by default, for example, the track by item.id)

Reduce the amount of rendered data (e.g. pedding, or taking a small portion of the data at a time, as needed)

Data flattening (e.g. for tree structures, using flattened structures, building a map and tree data, tree data changes are synchronized to the original flat data when operating on a tree because of the same reference to flat data)

In addition, for Angle 1.x, there is a problem with the Dirty Check and module mechanisms.


Q12, what do you think of the controller as syntax introduced in angular 1.2?

A: Until angular 1.2, any bindings on the view were directly bound to $scope

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

With controllerAs, you don't need to $scope, and the controller becomes a very simple javascript object (POJO), a more pure ViewModel.

function myCtrl(){
  // 使用 vm 捕获 this 可避免内部的函数在使用 this 时导致上下文改变
  var vm = this;
  vm.a = 'aaa';
}