What is the difference between ng-if and ng-show/hide?
The 1th difference is that ng-if creates this DOM node when the following expression is true, Ng-show is created at the initial time, and Display:block and Display:none are used to control the display and not display.
The 2nd difference is that Ng-if will (implicitly) produce new scopes, Ng-switch, Ng-include, and so on, dynamically creating an interface.
This will result in ng-if binding the Ng-model in the base variable and binding the model to another display area in the outer Div, and the outer layer will not change when the inner layers change, because it is already two variables at this time.
<p>{{name}}</p>
<div ng-if= "true" >
<input type= "text" ng-model= "name" >
</ Div>
Ng-show This problem does not exist because it does not have a first-level scope.
The way to avoid such problems is to always bind the elements in the page to the object's properties (data.x) rather than directly to the base variable (x).
See Scope in Angularjs
Ng-repeat an iterative algebra group, if there is an array of the same value, what will be the problem, how to solve?
The duplicates in a repeater are is prompted to not allowed. Add track by $index to resolve. Of course, you can also trace by any normal value, as long as you can uniquely identify each item in the array (establish the association between the DOM and the data).
Ng-click can be written in the expression, the use of JS native objects on the method?
Not only in the Ng-click expression, as long as in the page, can not directly invoke the native JS method, because these do not exist in the page corresponding to the Controller of the $scope.
Give me a chestnut:
<p>{{parseint (55.66)}}<p>
Will find nothing to show.
But if you add this function to the $scope:
$scope. parseint = function (x) {return
parseint (x);
}
So naturally there is no problem.
For this kind of demand, using a filter may be a good choice:
<p>{{13.14 | parseintfilter}}</p>
app.filter (' Parseintfilter ', function () {return
function ( Item) {return
parseint (item);
}
})
{now | ' Yyyy-mm-dd '} In this expression, how can the vertical and subsequent arguments be customized?
filter, format data, receive an input, follow a rule, and return processing results.
Built-in filter
Ng has a built-in filter of nine kinds:
Date (date)
Currency (currency)
LimitTo (limit array or string length)
Order BY (sort)
lowercase (lowercase)
Uppercase (capital)
Number (formatted numbers, plus thousands separator, and receive parameters to limit the number of decimal places)
Filter (handles an array, filtering out elements that contain a substring)
JSON (formatting a JSON object)
There are two ways to use filter, one is directly in the page:
<p>{{now | date: ' YYYY-MM-DD '}}</p>
The other is used in JS:
$filter (' Filter Name ') (object to filter, 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 filter, filter parameter 1, filter parameter 2,...) {
//... Do some things return
the processed object;
}
);
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 the method and data of the service in one object and return the object
App.factory (' Fooservice ', function () {return
{
target: ' Factory ',
sayhello:function () {
return ' Hello ' + this.target;
}}}
;
Service
Creates a service through a constructor, returning 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 via config, which is returned in $get to create the content 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;
}
}
}
});
The provider
app.config (function (fooserviceprovider) {
of Fooservice) is injected here. Fooserviceprovider.setconfigdata (' config data ');
From the underlying implementation, the service invokes factory, returns its instance, factory calls provider, and returns the content defined in its $get. Factory and service functions are similar, except that factory is a normal function, can return anything (returns can be accessed, so those private variables how to write, you understand); service is a constructor and can not be returned (bound to this can be accessed); Provider is the enhanced version factory, which returns a configurable factory.
See Angularjs's Factory vs Service vs Provider
What are the mechanisms used for angular data binding? Detail principle
Dirty check mechanism.
Bidirectional data binding is one of the core mechanisms of ANGULARJS. When there is any data change in the view, it will be updated to model, when the model data changes, view will also be synchronized update, obviously, this requires a monitoring.
The principle is that angular set up a listening queue on the scope model to monitor data changes and update view. Each time you bind a thing to the view, Angularjs inserts a $watch into the $watch queue to detect changes in the model it watches. When the browser receives an event that can be processed by the angular context, the $digest loop triggers, iterates through all the $watch, and updates the DOM.
Give me a chestnut.
<button ng-click= "val=val+1" >increase 1</button>
Click to produce an updated operation (at least two times $digest loop is triggered)
Press the button
The browser receives an event and enters the angular context
$digest loop starts and queries whether each $watch changes
The $watch of monitoring $scope. Val reports changes, so it is forced to perform a $digest loop again
No changes detected in the new $digest loop
The browser takes back the controller and updates the DOM for the new value of $scope. val
The upper limit of the $digest loop is 10 times (more than 10 times throws an exception to prevent infinite loops).
See Data binding on Angularjs
Two peer blocks A and B, what are the ways to let B know if an event is triggered in a? Detail principle
The question, in other words, is how to communicate between peer-interface modules. There are two methods, one being a shared service and one based on events.
Shared Services
In angular, a single instance object can be generated through factory, injected into modules A and B that require communication.
Based on event
There are two ways of doing this.
The first is the use of the Father Controller. Triggers ($emit) an event to the parent controller in the child controller, then listens to ($on) event in the parent controller, broadcasts ($BROADCAST) to the child controller, thus implements the number of arguments carried by the event According to the parent controller, it spreads between the siblings controller.
The second is the use of $rootScope. Each angular application defaults to a root scope $rootScope, the root scope is at the top level, and the scopes are hung down from it. Therefore, if the child controller uses $rootScope broadcast and receive events directly, then communication between siblings can be achieved.
See communication between Controller in Angularjs
How should a angular application be layered well?
Classification of directory structure
For small projects, you can organize them by file type, such as:
CSS
JS
controllers
models
Services
filters
templates
But for larger projects, it's best to divide 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 to store public things under modules.
Split of logical Code
As a MVVM framework, the angular application itself should be divided according to the model, the View model (Controller), and the view.
Here the logical code is split, mainly refers to try to make controller this layer is very thin. Extract the shared logic into the service (such as requests for background data, data sharing and caching, event-based communication between modules, etc., extract common interface operations into directive (such as date selection, paging, etc.), extract the common formatting operations into the filter and so on.
In complex applications, you can also create a corresponding constructor for the entity, such as the hard disk module, there may be a list, new, details such as several views, and corresponding to the controller, then you can build a disk constructor, which completes the data additions and deletions to check and verify operations, with Disk-related controller, injected into the disk constructor and generate an example, this example has the ability to add and delete changes to check and verify the method. This is both hierarchical and realized reuse (make the controller layer thinner).
The further practice of reference Angularjs in the Suningyun Center
Which routing libraries are commonly used in angular applications, and what are their differences?
Ngroute and Ui.router are common in angular1.x, and a new router (component-oriented) designed for ANGULAR2. The one in the back is not used in the actual project, it is not spoken.
The additional functionality of the framework, whether Ngroute or ui.router, must be introduced in the form of modular dependencies.
Difference
The Ngroute module is a angular routing module, and the Ui.router module is a third-party module developed based on the Ngroute module.
Ui.router is based on state, Ngroute is based on URLs, ui.router modules have more powerful functions, mainly embodied in the view of nesting.
Using Ui.router, you can define a route with an explicit parent-child relationship and insert the child routing template into the <div ui-view></div> of the parent routing templates through the Ui-view directive to implement the view nesting. This cannot be defined in Ngroute, and if the <div ng-view></div> is used in a parent-child view, it 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 '
})
What are some of the challenges that you might encounter if you plan a angular system through the directive?
Did not use directive to do a full set of components, can't tell.
One thing to think about is how components interact with the outside world and how they can be used with simple configuration.
Angular applications that are developed by different teams, and if they are to be integrated, what problems might be encountered and how to solve them?
Conflicts between different modules may be encountered.
For example, a team of all development under Modulea, another team developed code under MODULEB
Angular.module (' Myapp.modulea ', [])
. Factory (' ServiceA ', function () {
...
})
Angular.module (' Myapp.moduleb ', [])
. Factory (' ServiceA ', function () {
...
})
Angular.module (' myApp ', [' Myapp.modulea ', ' Myapp.moduleb '])
Will cause the ServiceA under two module to overwrite.
Seemingly in the angular1.x does not have a very good solution, so it is best to make a unified planning, good agreement, in strict accordance with the agreed development, each developer only write specific block code.
What are the disadvantages of angular?
Strong constraint
Lead to higher learning costs, not friendly to the front end.
But by complying with ANGULARJS's conventions, productivity will be high and be friendly to Java programmers.
Not conducive to SEO
Because all content is dynamically fetched and rendered, search engines cannot crawl.
One solution is that for normal user access, the server responds to the content of the Angularjs application, and for search engine access, it responds to HTML pages specifically for SEO.
Performance issues
As a MVVM framework, because of the two-way binding of data, there are performance problems for large arrays and complex objects.
Methods that can be used to optimize the performance of angular applications:
Reduce monitoring items (such as one-way binding to data that doesn't change)
Actively set the index (specify track by, the simple type defaults to its own index, the object uses $ $hashKey by default, for example, track by Item.id)
Reduce the amount of rendering data (such as paging, or take a small portion of data at a time, as needed)
Data flattening (for example, for a tree structure, using a flattened structure, building a map and tree-like data, when working on a tree, the tree-like data changes are synchronized to the original flat data because of the same reference to the flat data)
In addition, for angular1.x, there are problems of dirty checking and module mechanism.
Moving End
Can try ionic, but not perfect.
How do you see the January 2015 Peter-paul Koch's view of angular?
How do you view the controller as syntax introduced in angular 1.2?
The most fundamental benefit
Before angular 1.2, any bindings on the view were directly bound to the $scope
function Myctrl ($scope) {
$scope. A = ' AAA ';
$scope. foo = function () {
...
}
}}
With Controlleras, there is no need to inject $scope, controller becomes a very simple JavaScript object (POJO), a more pure ViewModel.
function Myctrl () {
//Use VM to capture this to prevent internal functions from using this to cause context to change the
var vm = this;
VM.A = ' aaa ';
}
Principle
From the point of view of the source code implementation, the Controlleras syntax simply creates an attribute on the $scope of an instance of the Controller object with the as alias.
if (Directive.controlleras) {
locals. $scope [Directive.controlleras] = controllerinstance;
}
But to do so, in addition to the above mentioned to make controller more POJO, you can also avoid encountering a angularjs scope-related pits (that is, the ng-if generated a level of scope above the pits, in fact, is also the JavaScript prototype chain inherits the value type of the pit. Because using Controlleras, all fields on the 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 with using Controlleras is that because there is no injection $scope, the methods under $watch such as $emit, $broadcast, $on, $scope are not available. These event-related operations can be encapsulated uniformly, or introduced $scope, special treatment in a single controller.
Reference angular controller as syntax vs scope
Detailing Angular's "dependency injection"
Chestnuts
Dependency Injection is a software design pattern designed to handle dependencies between code and reduce coupling between components.
For a chestnut, if you don't use Angularjs, and you want to query the data from the background and display it on the front end, you might want 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 arguments when you call render, you will be given an error as follows, because you cannot find El and HTTP (dependencies are defined, and dependencies are not automatically found when you run)
Render ();
Typeerror:cannot Read property ' get ' of undefined
And using Angularjs, you can do this directly.
function Myctrl = ($scope, $http) {
$http. Get ('/api/animals '). Success (function (data) {
$scope. Animals = Data
} )
}
In other words, when the angular App runs, it invokes Myctrl, automatically $scope and $http two dependency injections.
Principle
Angularjs is inferred by the constructor's parameter name to infer the dependent service name, through ToString () to find the corresponding string of the defined function, then parse out the parameters (dependencies) with the positive, then take the corresponding dependencies in the dependency map, and then pass it on.
Simplify it, presumably:
var inject = {
//Storage dependency mapping Relationship
storage: {},
//Registration dependent
register:function (name, Resource) {
this.storage[ Name] = Resource
,
//resolves dependencies and invokes
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);
}
}
}
Use this injector, the front that does not need to angularjs the chestnut so the transformation can call
Inject.register (' El ', Animalbox);
Inject.register (' Ajax ', HttpRequest);
Render = Inject.resolve (render);
Render ();
Problem
Because ANGULARJS's injector is to assume that the parameter name of the function is the name of the dependency, and then to look for dependencies, if the code is compressed (the parameter is renamed) after the previous pest, then the dependencies cannot be found.
Pre-compression
function Myctrl = ($scope, $http) {
...
}
After compression
function Myctrl = (A, b) {
...
}
Therefore, it is common to inject dependencies in the following two ways (the order in which dependencies are added is required).
Array annotation method
Myapp.controller (' Myctrl ', [' $scope ', ' $http ', function ($scope, $http) {
...
}])
An explicit $inject
Myapp.controller (' Myctrl ', Myctrl);
function Myctrl = ($scope, $http) {
...
}
Myctrl $inject = [' $scope ', ' $http '];
Add
For a DI container, you must have three elements: the registration of dependencies, the declaration of dependencies, and the acquisition of objects.
In Angularjs, both module and $provide can provide the registration of dependencies, the built-in injector can get objects (automatically complete dependency injection), and the Declaration of Dependencies, as mentioned in the previous question.
Here's a chestnut.
For module, the pass argument is more than one, representing the new module, the empty array represents not dependent on other modules
///Only one parameter (module name), representing the Get module
//Definition myApp, adding myapp.services for its dependencies
Angular.module (' myApp ', [' myapp.services ']);
Defines a services module that registers services under this module
angular.module (' myapp.services ', [])
//$provider have factory, s Ervice, provider, value, constant
//define a Httpservice
angular.module (' myapp.services '). Service (' Httpservice ', [' $http ', function ($http) {
...
}])
Reference
[Angularjs] realize a simple dependency injection on its own
Understanding module and injector in angular, i.e. dependency injection
The actual application scenario of dependency injection in Angularjs
How to treat ANGULAR2
Compared to the angular1.x,angular2, it is almost a completely new framework.
Based on typescript (which can be developed using typescript), strong language types are more advantageous when working with large project teams.
Component to improve the efficiency of development and maintenance.
There are also module supports dynamic loading, the native support of new router,promise, and so on.
Meet the future standards, absorb the advantages of other frameworks, it is worth looking forward to, but also to learn more things (ES Next, TS, RX, etc.).
The above is the ANGULARJS interview questions of the data collation, follow-up continue to supplement the relevant information thank you for your support of this site!