Home  >  Article  >  Web Front-end  >  13 front-end interview questions about angular (summary)

13 front-end interview questions about angular (summary)

青灯夜游
青灯夜游forward
2021-04-07 10:28:572476browse

This article summarizes and shares 13 front-end interview questions about angular. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

13 front-end interview questions about angular (summary)

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

The first difference is that ng-if only creates this dom node when the subsequent expression is true. ng-show is created initially, and uses display:block and display:none to control display or non-display.

The second difference is that ng-if will (implicitly) generate a new scope, ng-switch, ng-include The same is true for dynamically creating an interface later.

This will result in using basic variable binding ng-model in ng-if and binding this# in the outer layer p ##model Bind to another display area. When the inner layer changes, the outer layer will not change synchronously, because there are already two variables at this time.

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

Related tutorial recommendations: "

angular tutorial"

ng-show does not have this problem because it does not come with a first-level scope .

The way to avoid this kind of problem is to always bind the elements in the page to the properties of the object (data.x) rather than directly to the basic variable (x).

2. When ng-repeat iterates the array, if there are the same values ​​in the array, what will happen and how to solve it?

will prompt

Duplicates in a repeater are not allowed. Add track by $index to solve the problem. Of course, you can also trace by any ordinary value, as long as it can uniquely identify each item in the array (to establish the association between dom and the data).

3. Can the expression written in ng-click use methods on JS native objects?

Not only the expressions in

ng-click, but also the native JS methods cannot be directly called as long as they are on the page, because these are not Exists in the $scope of the Controller corresponding to the page.

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

factory: Put the methods and data of service in an object and return this object

service: Create a service through the constructor method and return an instantiated object

provider: Create a ## that can be configured through config #service, what is returned in $get is the content of service created with factoryFrom the perspective of underlying implementation,

service

calls factory and returns its instance; factory calls provider and returns the content defined in its $get. factory has similar functions to service, except that factory is an ordinary function and can return anything (return can be accessed, so you know how to write those private variables);

service

is a constructor and does not need to be returned (anything bound to this is can be accessed);

provider

is an enhanced version of factory, returning a configurable factory.

5. How to communicate between controllers in Angular?

1,

Service

2,

events

, specify the bound event 3, use

$rootScope

4,

controller

directly use $parent, $$childHead, etc. 5,

directive

Specify attributes for data binding

6. What mechanism does angular use for data binding? Describe the principle

The dirty check mechanism used, the so-called two-way binding, actually means that the operations on the interface can be reflected in the data in real time, and the changes in the data can be displayed in the interface in real time.

AngularJS

Use dirty value checking in $scope variables to implement two-way data binding, and you can listen to changes and trigger callbacks through $scope.$watch;

angular

uses a dirty checking mechanism. In angular, every time you bind something to your UI, you will Insert a $watch into the $watch queue. When our template is loaded, it is in the linking stage (Angular is divided into compile stage and linking stage - translator's note), the Angular interpreter will look for each directive, and then generate each required $watch. <p>当浏览器接受到可以被<code>angular context处理的事件时就会触发digest循环,这个循环是由两个更小的循环组合起来的,一个是$watch列表,一个是$evalAsync列表,而$watch列表在$digest循环中被“脏值检查”解析,在digest将会遍历我们的watch,然后询问它是否有属性和值的变化,直到$watch队列都检查过,在检查数据变化的时候,由于并不知道这个事件是对哪些数据进行了更改,以及这个事件有可能造成事件之外的其他任何地方的数据更改,所以必须进行一次大检查,将所有“注册”过的值全部检查一遍,一次检查称为一个周期,每次最少检查两遍,因为第二遍用来确认,前一遍的变动中是否有数据的变动,导致了其他数据的变动,如果第二次有变动的话,会再执行一遍,直到最后两次完全一致,则停止检查(其实就是个(递归(遍历))的过程),考虑到内存的消耗和死循环的风险,脏检查每个周期最多递归执行10遍,如果超过10遍就会抛出一个错误。当$digest循环结束时,DOM相应地变化。
angular

ng-click,ng-change,ng-blur...就是对各类用户事件的封装

$timeout,$http,$window,$location...就是对各种JS/API事件的封装

ng-model,以及控制器中的数据,就是对值的“注册”

$scope 本质是一个总的事件逻辑的封装容器,同时抽象为数据载体,实质上数据都存在于浏览器堆内存中

$scope.apply() & $scope.digest()Angular中的“数据大检查”的function

所以如果我们使用了非Angular封装的事件改编数据时,要手动执行一次大检查

由于Angular这种脏检查的方法效率不高,如果一个页面绑定的view超过2000个,就可能存在比较明显的性能问题,官方称之为“脏检查”

举个例子

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

click 时会产生一次更新的操作(至少触发两次 $digest 循环)

按下按钮浏览器接收到一个事件,进入到angular context

$digest 循环开始执行,查询每个 $watch 是否变化

由于监视$scope.val$watch 报告了变化,因此强制再执行一次 $digest 循环 新的 $digest 循环未检测到变化

浏览器拿回控制器,更新 $scope.val 新值对应的 dom

$digest 循环的上限是 10 次(超过 10次后抛出一个异常,防止无限循环)。

7、一个 angular 应用应当如何良好地分层?

目录结构的划分

对于小型项目,可以按照文件类型组织,比如:

css
js
  controllers 
  models 
  services 
  filters 
templates

但是对于规模较大的项目,最好按业务模块划分,比如:

css
modules
  account 
    controllers 
    models 
    services 
    filters 
    templates 
  disk 
    controllers 
    models 
    services 
    filters 
    templates

modules 下最好再有一个 common 目录来存放公共的东西。

逻辑代码的拆分

作为一个 MVVM 框架,Angular 应用本身就应该按照 模型,视图模型(控制器),视图来划分。

这里逻辑代码的拆分,主要是指尽量让 controller 这一层很薄。提取共用的逻辑到 service 中 (比如后台数据的请求,数据的共享和缓存,基于事件的模块间通信等),提取共用的界面操作到 directive 中(比如将日期选择、分页等封装成组件等),提取共用的格式化操作到 filter 中等等。

在复杂的应用中,也可以为实体建立对应的构造函数,比如硬盘(Disk)模块,可能有列表、新建、详情这样几个视图,并分别对应的有 controller,那么可以建一个 Disk 构造函数,里面完成数据的增删改查和验证操作,有跟 Disk 相关的 controller,就注入 Disk 构造器并生成一个实例,这个实例就具备了增删改查和验证方法。这样既层次分明,又实现了复用(让 controller 层更薄了)。

8、angular 应用常用哪些路由库,各自的区别是什么?

Angular1.x 中常用 ngRouteui.router,还有一种为 Angular2 设计的 new router(面向组件)。后面那个没在实际项目中用过,就不讲了。

无论是 ngRoute 还是 ui.router,作为框架额外的附加功能,都必须以 模块依赖 的形式被引入。

区别

ngRoute 模块是 Angular 自带的路由模块,而 ui.router 模块是基于 ngRoute模块开发的第三方模块。

ui.router 是基于 state (状态)的, ngRoute 是基于 url 的,ui.router模块具有更强大的功能,主要体现在视图的嵌套方面。

使用 ui.router 能够定义有明确父子关系的路由,并通过 ui-view 指令将子路由模版插入到父路由模板的 82a3d26c8f4a2e3756041f5a82c4d9fb94b3e26ee717c64999d7867364b1b4a3中去,从而实现视图嵌套。而在 ngRoute 中不能这样定义,如果同时在父子视图中 使用了 a934de6ad8c4c54b22e1e931400cb97894b3e26ee717c64999d7867364b1b4a3会陷入死循环。

分属不同团队进行开发的 angular 应用,如果要做整合,可能会遇到哪些问题,如何解决?
可能会遇到不同模块之间的冲突。

比如一个团队所有的开发在 moduleA 下进行,另一团队开发的代码在 moduleB 下

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

angular.module('myApp', ['myApp.moduleA', 'myApp.moduleB'])

会导致两个 module 下面的 serviceA 发生了覆盖。

貌似在 Angular1.x 中并没有很好的解决办法,所以最好在前期进行统一规划,做好约定,严格按照约定开发,每个开发人员只写特定区块代码。

9、angular 的缺点有哪些?

强约束

导致学习成本较高,对前端不友好。

但遵守 AngularJS 的约定时,生产力会很高,对 Java 程序员友好。

不利于 SEO

因为所有内容都是动态获取并渲染生成的,搜索引擎没法爬取。

一种解决办法是,对于正常用户的访问,服务器响应 AngularJS 应用的内容;对于搜索引擎的访问,则响应专门针对 SEO 的HTML页面。

性能问题

作为 MVVM 框架,因为实现了数据的双向绑定,对于大数组、复杂对象会存在性能问题。

可以用来 优化 Angular 应用的性能 的办法:

减少监控项(比如对不会变化的数据采用单向绑定)

主动设置索引(指定 track by,简单类型默认用自身当索引,对象默认使用 $$hashKey,比如改为 track by item.id
降低渲染数据量(比如分页,或者每次取一小部分数据,根据需要再取)

数据扁平化(比如对于树状结构,使用扁平化结构,构建一个 map 和树状数据,对树操作时,由于跟扁平数据同一引用,树状数据变更会同步到原始的扁平数据)

另外,对于Angular1.x ,存在 脏检查模块机制 的问题。

移动端

可尝试 Ionic,但并不完善。

10、解释下什么是$rootScrope以及和$scope的区别?

通俗的说$rootScrope 页面所有$scope的父亲

如何产生$rootScope$scope吧。

step1:Angular解析ng-app然后在内存中创建$rootScope

step2:angular回继续解析,找到{{}}表达式,并解析成变量。

step3:接着会解析带有ng-controllerp然后指向到某个controller函数。这个时候在这个controller函数变成一个$scope对象实例。

**11、如何取消 $timeout, 以及停止一个$watch()? **

停止 $timeout我们可以用cancel

var customTimeout = $timeout(function () {
 // your code
}, 1000);
$timeout.cancel(customTimeout);

停掉一个$watch

// .$watch() 会返回一个停止注册的函数

function that we store to a variable
var deregisterWatchFn = $rootScope.$watch(‘someGloballyAvailableProperty', function (newVal) {
 if (newVal) {
  // we invoke that deregistration function, to disable the watch 
  deregisterWatchFn(); 
  ... 
 }
});

12、Angular Directive中restrict 中分别可以怎样设置?scope中@,=,&有什么区别?

restrict中可以分别设置:

A匹配属性

E匹配标签

C匹配class

M 匹配注释

当然你可以设置多个值比如AEC,进行多个匹配。

在scope中,@,=,&在进行值绑定时分别表示

@获取一个设置的字符串,它可以自己设置的也可以使用{<!-- -->{yourModel}}进行绑定的;

= 双向绑定,绑定scope上的一些属性;

&用于执行父级scope上的一些表达式,常见我们设置一些需要执行的函数

13、$apply()$digest()的区别

Security: $apply() can receive a parameter as function(), this function will be wrapped in a try … catch block, so once an exception occurs, the exception will be handled by $exceptionHandler service.

$apply will cause ng to enter $digest cycle and start traversing from $rootScope (depth first) Check for data changes.

$digestOnly this scope and its children scope will be checked. When you are sure that the current operation only affects them, use $digest Could improve performance slightly.

For more programming related knowledge, please visit: Programming Video! !

The above is the detailed content of 13 front-end interview questions about angular (summary). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete