Home>Article>Web Front-end> 18 common angular interview questions (with answer analysis)
This article summarizes and shares 18 commonangularinterview questions (with answer analysis) to help you sort out basic knowledge and enhance your angular knowledge reserve. It is worth collecting, come and take a look!
#1. What mechanism does angular use for data binding? Describe the principle in detail
Answer: Dirty checking mechanism.
Analysis:
Two-way data binding is one of the core mechanisms of AngularJS. When any data changes in the view, it will be updated to the model. When the data in the model changes, the view will also be updated synchronously. Obviously, this requires monitoring. [Related tutorial recommendations: "angular tutorial"]
The principle is that Angular sets a listening queue on the scope model to monitor data changes and update the view. Every time you bind something to the view, AngularJS will insert a $watch into the $watch queue to detect whether there are changes in the model it monitors. When the browser receives an event that can be processed by the angular context, the $digest loop is triggered, traverses all $watches, and finally updates the dom.
2. How is AngularJS’s two-way data binding implemented?
Answer:
1. Each two-way bound element has a watcher
2. When certain events occur, digest dirty data is called detection.
These events include: content changes of form elements, Ajax request responses, functions executed by clicking buttons, etc.
3. Dirty data detection will detect all watcher elements under the rootscope.
$digest function is dirty data monitoring
3. What third-party plug-ins have you used in angularjs project development
Answer: AngularUi ui-router oclazyload etc. Attached is an article to take a closer look at https://segmentfault.com/a/1190000003858219
4. The difference between ng-show/ng-hide and ng-if ?
Answer: We all know that ng-show/ng-hide actually hides and displays through display. And ng-if actually controls the addition and deletion of dom nodes. Therefore, if we load dom nodes based on different conditions, then the performance of ng-if is better than ng-show.
5. Explain what is r o o tSc r o p e and rootScrope and rootScrope and the difference between it and scope?
Answer: In layman's terms, r o o tScrope page is the father of all rootScrope pages and all scopes of all rootScrope pages.
Analysis:
Let’s take a look at how to generate r o o tSc o p e and rootScope and rootScope and scope.
step1:Angular parses ng-app and creates $rootScope in memory.
step2: angular continues parsing, finds the {{}} expression, and parses it into a variable.
step3: Then the div with ng-controller will be parsed and pointed to a controller function. At this time, the controller function becomes a $scope object instance.
6. List at least three ways to implement communication between different modules?
Answer:
7. What is the expression { {yourModel}}? work?
Answer:
It relies on the $interpolation service. After initializing the page html, it will find these expressions and mark them, so every time it encounters a { { }} , a $watch will be set. $interpolation will return a function with context parameters. When the function is finally executed, the expression is $parse to that scope.
8. $http in angular
Answer: $http is a core service in AngularJS, used to read data from remote servers.
We can use the built-in http service to communicate directly with the outside world. The http service communicates directly with the outside world. The http service communicates directly with the outside world. The http service simply encapsulates the browser's native XMLHttpRequest object.
9. When ng-repeat iterates the array, if there are the same values in the array, what will happen and how to solve it?
Answer: It will prompt that 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 (establish the association between dom and data)
10. Is angularjs mvc or mvvm framework
Answer: mvvm
Analysis:
First explain your understanding of mvc and mvvm:
Why do we need it in the first place? MVC? Because as the size of the code becomes larger and larger, dividing responsibilities is the general trend, and for the convenience of later maintenance, modifying one function does not affect other functions. And for reuse, because a lot of the logic is the same. MVC is just a means, the ultimate goal is modularization and reuse.
Advantages of mvvm
Low coupling: View can be changed and modified independently of Model, and the same ViewModel can be reused by multiple Views; and changes in View and Model can not affect each other;
Reusability: Yes Put some view logic in ViewModel to reuse multiple Views;
Independent development: developers can focus on the development of business logic and data (ViewModemvvmdi) and designers can focus on the design of UI (View);
Testability: Clear View layering makes it easier and simpler to test the business logic of the presentation layer.
The MVVM pattern in angular is mainly divided into four parts:
View: It focuses on the display and rendering of the interface. In angular, it is a view template containing a bunch of declarative Directives.
ViewModel: It is the glue of View and Model, responsible for View and Model interaction and collaboration, it is responsible for providing displayed data to the View, and providing a way for the Command event in the View to operate the Model; in angular, the $scope object plays the role of the ViewModel;
Model: It is It is an encapsulation carrier of data related to the business logic of the application. It is an object in the business domain. The Model does not care about how it will be displayed or operated, so the model does not contain any logic related to interface display. In a web page, most Some Models return data from the Ajax server or are global configuration objects; while the service in Angular is a place to encapsulate and process the business logic related to the Model. This type of business service can be used by multiple Controllers or Domain services reused by other services.
Controller: This is not the core element of the MVVM pattern, but it is responsible for the initialization of the ViewModel object. It will combine one or more services to obtain the business domain Model and place it in the ViewModel object. on, so that the application interface reaches a usable state when starting to load.
The interface of mvc is closely related to the logic, and the data is read directly from the database. The interface of mvvm is loosely coupled with the viewmode, and the interface data comes from Obtained from viewmodel. So angularjs prefers mvvm
11. What roles do $scope, controller, directive and service play in mvvm in angularjs
Answer: If you I don’t know, the analysis of the first question is very clear, read it carefully again
12. How do you control the reasonable loading of static resources in the angular project
Answer: None
13. What do you need to pay attention to when writing controller logic?
Answer:
1. Simplify the code (this is required by all developers)
2. Resolutely not operate the dom node. You may ask at this time Why not?
Your answer is: DOM operations can only appear in directives. The last place it should appear is in service. Angular advocates test-driven development. If DOM operations appear in service or controller, it means that the test cannot pass. Of course, this is just one point. What is important is one of the benefits of using Angular, which is two-way data binding, so that you can focus on processing business logic without having to deal with piles of DOM operations. If the Angular code is still full of various DOM operations, then why not just use jquery to develop it.
What is test-driven development? To popularize it:
Test-driven development, the full English name is Test-Driven Development, or TDD for short, is a new development method that is different from the traditional software development process. It requires writing test code before writing the code for a certain function, and then only writing the functional code that makes the test pass, and driving the entire development through testing. This helps write concise, usable and high-quality code and speeds up the development process.
14. How to communicate between controllers
Answer:
1. event
There are two ways here, one One is scope.scope.emit, and then obtains parameters by listening to rootScope's event; the other is rootScope's event to obtain parameters; the other is rootScope's event to obtain parameters; the other is rootScope.b r o a d c a s t , by Listen to broadcast, obtain parameters by listening to broadcast, and listen to scope events.
There is no performance difference between these two methods in the latest version of Angular. The main reason is that the direction of event sending is different. You can choose according to the actual situation.
2. service
You can create a dedicated event Service, or you can split it according to business logic and store the data in the corresponding Service
3.$rootScope
This method may be a bit dirty, but it is more convenient, that is, the data is stored in rootScope, so that each sub-rootScope is in each sub-rootScope, so that each sub-scope can be called, but it needs to be noted. Let’s look at the life cycle
4. Directly use sc o p e . scope.scope.$nextSibling and similar properties
Similar ones include sc o p e . scope.scope.parent. This method has more disadvantages. Officially, it is not recommended to use any attributes starting with $$. It not only increases coupling, but also needs to deal with asynchronous issues, and the order of scope is not fixed. Not recommended
The other way is to pass parameters through local storage, global variables or postMessage of modern browsers. Unless there are special circumstances, please avoid this method.
15. Several parameters of custom instructions
Answer:
Let’s talk about a few commonly used ones such as:
restrict: The declaration form of the instruction in dom E (element) A (attribute) C (class name) M (comment)
template: two forms, one HTML text; one function that can accept two parameters, tElemetn and tAttrs, and returns a string representing the template. The template string must have a root DOM element
templateUrl: two forms, one is a string representing the path of the external HTML file; a function that can accept two parameters, the parameters are tElement and tAttrs, and returns a String for path to external HTML file
compile (object or function): The compile option can return an object or function. If the compile function is set, it means that we want to perform DOM operations before instructions and real-time data are placed in the DOM. It is safe to perform DOM operations such as adding and deleting nodes in this function. Essentially, when we set the link option, we actually create a postLink() link function so that the compile() function can define the link function.
Then there is the portal: http://www.cnblogs.com/mliudong/p/4180680.html
The difference between compile and link:
When compiling , compile converts the dom, and saves it first when it encounters the bound listener. Several are saved, and finally they are summarized into a link function and executed together, which improves performance.
16. The difference between angular and jquery
Answer:
angular is based on data-driven, so angular is suitable for projects with complicated data operations ( Here you can mention the single-page application again. If you don’t know how, the benefits are here again http://www.zhihu.com/question/20792064)
jquery is based on dom driver, and jquery is suitable for doing many dom operations. Project
17. How much do you know about the form form in angular
Answer:
Angular has extended the type of the input element and provided a total of The following 10 types:
text
number
url
radio
checkbox
hidden
#button
submit
reset
Angular for the form There are 4 built-in CSS styles.
ng-valid Verify legal status
ng-invalid Verify illegal status
ng-pristine If you want to use the native form, you need to set this value
ng-dirty The form is in dirty data state
Angular is processing the form When performing automatic verification, the attributes on the Model will be verified. If ng-model is not set, Angular cannot know whether the value of myForm.$invalid is true.
Verification content
required Indicates whether to enter content
ng-maxlength Maximum length
ng-minlength Minimum length
Example: Portal https://github.com/18500047564/clutter
18. How much do you know about what filter is? Implement a custom filter
Answer:
date(date)
currency(currency)
limitTo (limit array or string length)
orderBy (sort)
lowercase (lowercase )
uppercase (uppercase)
number (format number, add thousands separator, and receive parameters to limit the number of decimal points)
filter (process an array, filter out elements containing a certain substring)
json (formatted json object)
There are two ways to use filter,
One is directly in the page:
{{now | date : ‘yyyy-MM-dd’}}
The other is used in js:
$filter(‘过滤器名称’)(需要过滤的对象, 参数 1, 参数 2,…) $filter(‘date’)(now, 'yyyy-MM-dd hh:mm:ss’);
Customize a deduplication array
app.filter("unique", function() { return function(arr) { var n = []; var obj = {}; for (var i = 0; i < arr.length; i++) { if (!obj[arr[i]]) { n.push(arr[i]); obj[arr[i]] = 1; } } return n; }; });
For more programming-related knowledge, please visit:Programming Tutorial! !
The above is the detailed content of 18 common angular interview questions (with answer analysis). For more information, please follow other related articles on the PHP Chinese website!