Angulajs Actual Combat summary

Source: Internet
Author: User
Tags emit

First, AngularJS initialization loading process

1. The browser loads the HTML and parses it into DOM.

2. The browser loads the Angular.js script.

3, Angularjs wait until domcontentloaded event triggered.

4, Angularjs look for the NG-APP directive, this directive indicates the application boundary.

5. Use the module specified in Ng-app to configure the injector ($injector).

6, the injector ($injector) is used to create a "build service ($compile services)" and "root scope ($rootScope)".

7. The compilation Service ($compile service) is used to compile the DOM and link it to the root scope ($rootScope).

8. The ng-init instruction assigns "world" to the name variable in the scope.

9. With the substitution of {{name}}, the entire expression becomes "Hello world".

Second, AngularJS Provider/service/factory

1. What is Provider?

Provider can provide a common service for your application, either as a constant or as an object. For example, $http that we inject into the controller, $scope can be thought of as provider.

App.controller (' Mainctrl ', function ($scope, $http) {
$http. Get (...). Then (...);
}

2, provider

Now let's customize a provider for ourselves.

Method 1
$provide. Provider (' Test ', {
N:1;
$get: function () {
return n;
};
});
Method 2
$provide. Provider (' Test ', function () {
THIS.N = 2;
this. $get = function () {
return n;
};
});
Use
App.controller (' Mainctrl ', function ($scope, test) {
$scope. test = test;
});

Let's take a look at provider's internal implementation code

function provider (name, Provider_) {
if (Isfunction (Provider_)) {
Provider_ = Providerinjector.instantiate (Provider_);
}
if (!provider_. $get) {
Throw Error (' Provider ' + name + ' must define $get factory method. ');
}
return providercache[name + providersuffix] = Provider_;
}

You can see that the basic principle of provider is to implement a singleton injection by implementing a $get method, which is the result of $get execution.

3, Factory

Is it a hassle to write a $get every time? OK, so we have a factory. Factory can be said to be a variant of provider, the second parameter in the method is the content in the $get.

Define Factory
$provide. Factory (' DD ', function () {
return new Date ();
});
Use
App.controller (' Mainctrl ', function ($scope, DD) {
$scope. mydate = DD;
});

Factory implementation of the source code:

function factory (name, FACTORYFN) {

Return provider (name, {

$get: FACTORYFN
});
}

4. Service

In the case of factory we still need to return the new object, and the service is simpler, this step will save you, his second parameter is the object class you want to return, that is, the new one you do not have to work. Cool enough, huh?

Define Service

$provide. Service (' DD ', Date);

The following is the implementation source code for the service:

function service (name, constructor) {
Return factory (name, [' $injector ', function ($injector) {
Return $injector. Instantiate (constructor);

}]);
}

Then the factory and service bring code streamlining while also losing some of the features. The services defined by provider can be configured through the module CONFIG.

Iii. AngularJS adding elements and deleting elements dynamically

$scope. Username= ' Welcome to Angular world! ';
$scope. Test = function Test () {
Console.log (' Angular dynamic add element ');
}
Dynamically compiling HTML via $compile
var html= "<div ng-click= ' Test () ' >}</div> ';
var template = angular.element (HTML);
var mobiledialogelement = $compile (template) ($scope);
Angular.element (document.body). Append (mobiledialogelement);
Remove removes the Created element
var closemobiledialog = function () {
if (mobiledialogelement) {
Mobiledialogelement.remove ();
}

Iv. Broadcast and reception of AngularJS events

Send message: $scope. $emit (name, data) or $scope. $broadcast (name, data);

Receive message: $scope. On (name,function (event,data) {});

Difference: $emit Broadcast to the parent controller $broadcast broadcast to the child controller

Broadcast is an event that is broadcast from the sender to his child scope.

Here is Parentcontroller send, Parentcontroller and Childcontroller will receive, and Maincontroller will not receive

$emit broadcast to the parent controller, the parent controller is able to receive the message

$on have two parameter function (EVENT,MSG) The first parameter is the event object, and the second parameter is the receipt of the message information

Angular.module (' onbroadcastevent ', [' ng '])
. Controller (' Maincontroller ', function ($scope) {
$scope. $on (' To-maincontroller ', function (event,msg) {
Console.log (' Maincontroller Received: ' + msg);
});
})
. Controller (' Parentcontroller ', function ($scope) {
$scope. Click = Function (msg) {
$scope. $emit (' To-maincontroller ', MSG + ', from Parentcontroller to Maincontroller ');
$scope. $broadcast (' To-childcontroller ', MSG + ', from Parentcontroller to Childcontroller ');
$scope. $broadcast (' To-brothercontroller ', MSG + ', from Parentcontroller to Brothercontroller ');
}
})
. Controller (' Childcontroller ', function ($scope) {
$scope. $on (' To-childcontroller ', function (event,msg) {
Console.log (' Childcontroller Received: ' + msg);
});
})
. Controller (' Brothercontroller ', function ($scope) {
$scope. $on (' To-brothercontroller ', function (event, msg) {
Console.log (' Brothercontroller Received: ' + msg);
});
});

V. Examples of AngularJS Promise deferred

var app = Angular.module (' app ', [' AutoComplete ']);
App.factory (' suggestion ',
function ($http, $q, $timeout) {
var suggestion = new Object ();
Suggestion.getdata = function (keyword) {
var deferred = $q. Defer ();
$http. Get (' http://codesearch.sinaapp.com/search.php ',
}). Success (function (data) {
Deferred.resolve (data);
});
return deferred.promise;
}
return suggestion;
});
App.controller (' Mysuggestionctrl ',
function ($scope, $sce, suggestion) {
$scope. autoComplete = function (keyword) {
if (keyword) {
Suggestion.getdata (keyword). then (function (data) {
var dataList = data.split (' | ');
$scope. dataList = dataList;
});
}
}
});
Multiple Promise instances:
var data2= "222";
var promises = [];
var deffered1 = $q. Defer ();
var deffered2 = $q. Defer ();
$timeout (function () {
Deffered1.resolve (DATA1);
},2000);
$timeout (function () {
Deffered2.resolve (DATA2);
},2000);
Promises.push (deffered1.promise);
Promises.push (deffered2.promise);
$q. All (promises) and then (function (data) {
Console.log (data);
});
Output: ["111", "222"] the order of an array object is consistent with the order of the push

  

Vi. AngularJS global scope and isolate scope communication


I. Scope scope
1, in Angularjs, child scopes generally inherit the properties and methods of their parent scope through the JavaScript prototype inheritance mechanism. There is one exception: using scope in directive: {...}, the scope created in this way is a separate "Isolate" scope, which also has a parent scope, but the parent scope is not on its prototype chain and does not prototype the parent scope. This way of defining scopes is typically used to construct reusable directive components.

2. If we access a property defined in a parent scope in a child scope, JavaScript first looks for the property in the child scope, does not find it, and then looks for it from the parent scope on the prototype chain, if it is not found, then the parent scope of the upper-level prototype chain. In Angularjs, the top of the scope prototype chain is $rootscope,javascript looking up to $rootscope.

3. Scope: {...}-directive creates a separate "Isolate" scope with no prototype inheritance. This is the best choice for creating reusable directive components. Because it does not directly access/modify the properties of the parent scope, no unintended side effects occur.


Ii. Isolate Scope Reference modifier
1, = or =attr the properties of the "Isolate" scope and the parent scope of the properties of two-way binding, the modification of either side affects the other side, this is the most common way;

2, @ or @attr the property of the Isolate scope is one-way bound to the property of the parent scope, that is, the "Isolate" scope can read only the value of the parent scope, and the value is always of type string;

3, & or &attr the "Isolate" scope to wrap the attributes of the parent scope into a function that reads and writes the properties of the parent scope as a function, and the wrapper method is $parse


Third, Directive and controller data transmission and communication
1. The parent controller listens to the global scope (parent scope) variable and broadcasts the event to the child scope (Directive scope, each Directvie has its own independent scope scope)

2. Directive defines the local scope, which refers to the global scope through the =, @, & (method) character display

3, Directive scope (sub scope) through parent[$scope. $parent. xxx] Referencing the properties of the global scope

4, Directive monitor global scope variable change, can pass $scope. $parent. $watch method

Iv. Explanation of examples

Http://www.cnblogs.com/hubcarl/p/4202053.html

Vii. AngularJS $apply vs $digest

$apply will allow NG to enter $digest cycle and traverse (depth first) from $rootscope to check for data changes.
The $digest only checks the scope and its child scopes, and with $digest you can slightly improve performance when you are certain that the current operation only affects them.
Some unnecessary operation, put in $timeout inside delay execution.
If data changes are not involved, you can also add a third parameter, false, to avoid calling $apply.
The $evalasync executed in directive will be executed before the browser renders after angular operation of the DOM.
The $evalasync executed in the controller is executed before the angular operation of the DOM, which is generally not used.
The use of $timeout will be performed after the browser renders.
Time is required, the second parameter can be set to 0.

$http. Get (' Http://path/to/url '). Success (function (data) {
$scope. name = Data.name;
$timeout (function () {
Do sth later, such as log
}, 0, false);
});

Details: HTTPS://GITHUB.COM/ATIAN25/BLOG/ISSUES/5

Eight, AngularJS Directive learning examples

1, restrict it restricts directive to the specified declaration method. If omitted, directive will only allow the property declaration

E-element name: <my-directive></my-directive>

A-Attribute name: <div my-directive= "Exp" ></div>

C-class Name: <div class= "MY-DIRECTIVE:EXP;" ></div>

M-Note: <!--directive:my-directive Exp--and

2. Dialog instances

<! DOCTYPE html>



<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>

<title>directive-dialog</title>

<meta content= "ie=edge,chrome=1" http-equiv= "x-ua-compatible" >

<script src= ". /.. /sea-modules/angular/angularjs/1.1.5/angular.js "></script>


<body>

<div ng-controller= "Myctrl" >

<button ng-click= "Show=true" >show</button>

<dialog title= "Hello}"

Visible= "}"

On-cancel= "Show=false;"

On-ok= "Show=false;methodinparentscope ();" >

<!--above On-cancel, On-ok, is referenced through & in Directive's isoloate scope.

If the expression contains a function, you need to bind the function to the parent scope (currently the scope of Myctrl)--

Body goes here:username:}, Title:}.

<ul>

<!--You can play like this here. ~names is the parent scope--

<li ng-repeat= "name in Names" >}</li>

</ul>

</dialog>

</div>

<script type= "Text/javascript" >

var mymodule = angular.module ("Dialog", []);

Mymodule.controller ("Myctrl", function ($scope) {

$scope. Names = ["Name1", "name2", "Name3"];

$scope. Show = false;

$scope. Username = "Carl";

$scope. title = "Parent title";

$scope. Methodinparentscope = function () {

Alert ("What is defined in scope through & is defined in the parent scope!!") ");

};

});

Mymodule.directive (' dialog ', function Factory () {

return {

PRIORITY:100,

template:[' <div ng-show= ' visible ' > ',

'
' <div class= ' body ' ng-transclude></div> ',

' <div class= ' footer ' > ',

' <button ng-click= ' onOk () ">OK</button>",

' <button ng-click= ' OnCancel () ">Close</button>",

' </div> ',

' </div> '].join (""),

Replace:false,

Transclude:true,

Restrict: ' E ',

scope:{

Title: "@",//refers to the value of the dialog tag Title property

OnOk: "&",//the contents of the On-ok attribute referencing the dialog tag in wrapper function form

OnCancel: "&",//the contents of the On-cancel attribute referencing the dialog tag in wrapper function form

Visible: "@"//reference the value of the dialog label Visible property

}

};

});

</script>

</body>

Ix. Summary of matters needing attention and questions of AngularJS (to be continued)

Beware that using note angular.module (' MyModule ', []) and the use of Angular.module (' MyModule ')

Angular.module (' MyModule ', []) would create the module mymodule and overwrite any existing module namedmymodule.

>>>angular.module (' MyModule ', []) Create a new module that overrides the already existing module

Use the Angular.module (' MyModule ') to retrieve an existing module.

>>>angular.module (' MyModule ') points to the already existing module

Angulajs Actual Combat summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.