Angular FAQ and angularjs FAQ
1. 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.
#2. What is the problem if the array has the same value when ng-repeat iterates the array?
The message 'duplicates in a repeater are not allowed. 'plus 'track by $ Index' is displayed. 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 ).
#3. Can the expressions written in ng-click use methods on JS native objects, such as Math. max? Why?
No. As long as it is on the page, you cannot directly call the native JS method, because these do not exist in the $ scope of the Controller corresponding to the page. Unless this function is added to $ scope:
'''Javascript
$ Scope. parseInt = function (x ){
Return parseInt (x );
}'''
#4. {now | 'yyyy-MM-dd'} in this expression, how can the vertical bars and the following parameters be customized?
Definition method:
App. filter ('filter name', function (){
Return function (object to be filtered, filter parameter 1, filter parameter 2 ,...){
//... Do something
Return: the object after processing;
}
});
You can use either of the following methods:
Javascript <p >{{ now | date: 'yyyy-MM-dd' }}</p>
One 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 ');
#5. What is the relationship between factory and service and provider?
Factory puts the methods and data of the service in an object and returns this object. The service creates a service through a constructor and returns an instantiated object. The provider creates a service that can be configured through config.
At the underlying implementation level, the service calls the factory and returns its instance. The factory calls the provider and places the defined content in $ get to return. Factory and service functions are similar, except that factory is a common function and can return anything (return can be accessed, so how do you know about private variables); 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.
#6. What mechanism does angular use for data binding? Detailed Principles of dirty checking.
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 ).
#7. two levels of interface blocks a and B. If an event is triggered in a, which of the following methods can let B know and elaborate on the principle, .)
There are two methods: sharing services and event-based.
A. 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.
B. 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.
#8. How should an angular application be well layered?
There are two points
A. directory structure division
Small projects can be organized by file type, such as css
Js
Controllers
Models
Services
Filters
Templates
However, for large projects, it is best to divide them by business modules, such as css.
Modules
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.
B. Logic Code Division
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 ).
#9. 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.
The difference between the two is:
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.
#10. What are the challenges if you plan a fully componentized system through angular direve ve?
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.
#11. 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. lelea', '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.
#12. What are the disadvantages of angular?
A. Strong Constraints
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.
B. 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.
C. 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)
D. Mobile Terminal
#13. How do I view the controller as syntax introduced in angular 1.2?
Before angular 1.2, any binding on the view was directly bound to $ scope. With controllerAs, you do not need to inject $ scope. controller becomes a very simple javascript Object (POJO), a more pure ViewModel.
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 ).
However, if you do not introduce $ scope, a problem occurs. As a result, $ emit, $ broadcast, $ on, $ watch, and other $ scope methods 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.
#14. Elaborate on angular's "dependency injection"
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.
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 simply like the following, after the code is compressed (the parameter is renamed ), the dependency cannot be found.
Function myCtrl = ($ scope, $ http ){
...
}
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'];
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, the two methods above.
#15. What is the difference between controller as and controller and what problems can be solved?
When using the controller, inject $ window and $ scope to the controller. In this case, the attributes and methods in the controller belong to $ scope, and when using controllerAS, you can define controller as a Javascript prototype class and bind the properties and methods of the prototype in html.
Advantages:
A. You can use the Javascript prototype class. We can use a more advanced ES6 or TypeScript to write Controller;
B. Avoid some problems caused by the so-called child scope prototype inheritance.
Controller:
Angular. module ('app', []). controller ('testcontroller', TestController );
TestController. $ inject = ['$ scope', '$ window'];
Function TestController ($ scope, $ window ){
$ Scope. name = 'beginor ';
$ Scope. greet = greet;
Function greet (){
$ Window. alert ('hello, '+ $ scope. name );
}
}
Use in HTML:
<Div ng-Controller = "TestController">
<Label> Name:
<Input type = "text" ng-model = "name"/>
</Label>
<Button type = "button" ng-click = "greet ()">
</Div>
ControllerAS:
Angular. module ('app', []). controller ('testcontroller', TestController );
TestController. $ inject = ['$ window'];
Function TestController ($ window ){
This. name = 'beginor ';
This. $ window = $ window;
}
TestController. prototype. greet = function (){
This. $ window. alert ('hello, '+ this. name );
}
Use in HTML:
<Div ng-Controller = "TestController as vm">
<Label> Name:
<Input type = "text" ng-model = "vm. name"/>
</Label>
<Button type = "button" ng-click = "vm. greet ()">
</Div>
# 16.html: {currentDate ()} js: $ scope. currentDate = function () {return new Date ();} is there any problem with this method?
If there is a problem, the time changes in real time, and the data will be updated continuously, with low efficiency. The dirty data will not be checked again after 10 times;
Solution: You can use a variable to receive function calls.
#17. How does directive call external functions, how does one pass parameters to functions, and how does one expose functions to external calls?
#18. What are the functions of compiled and link functions in custom commands? What are their application scenarios?
#19. Differences between knockoutjs, angularjs, backbone, and handlebars
Knockoutjs: small size, good compatibility, complicated business code, and average performance
Backbone: lightweight applications
Handlerbars: A template library, usually static templates.
Angularjs: it is a framework that includes the template, but the interface is not only a template, but also some configuration items that can be specified.