Angularjs Learning Notes-$http, data rendering to tables, routing, dependency injection, provider

Source: Internet
Author: User

1-$http

A larger data set can be obtained from the server, where the built-in service using ANGULARJS is called $http. Use Angularjs's dependency injection to service the controller of the Phonelist component.

Using Angularjs's $http service in our controller, make an HTTP request to our Web server to get the data in the file.

App/phone-list/phone-list.component1.js:

  Angular.module (' phonelist '). Component (' Phonelist ', {     templateurl: ' phone-list/phone-list.template.html ',     controller:function Phonelistcontroller ($http) {         var = this;         Self.orderprop = ' age ';         $http. Get (' Phones/phones.json '). Then (function (response) {             self.phones = response.data;         });}     );

PS: $http make an HTTP GET request to the Web server, where the URL is the JSON file address. The server responds by providing the data in the JSON file. (Responses can also be generated dynamically by back-end servers)

The $http service returns a Promise object that has a method to handle the asynchronous response and assign the telephony data to the controller as a property. PS:ANGULARJS detects a JSON response and resolves it to the property of the object passed to our callback.

Since phones assigns this property in a callback function where this does not define a value, a local variable self is introduced to point to the controller instance.

Ps: To use a service in ANGULARJS, simply declare the name of the desired dependency as a parameter to the controller constructor:

function Phonelistcontroller ($http) {...}

When building a controller, ANGULARJS's dependency injector serves your controller. The dependency injector is also responsible for creating any lazy nature that the service may have. (services are usually dependent on other services). Ps: Parameter names are important because the injector uses these to find dependencies.

$http service is a core ANGULARJS service that facilitates communication with a remote HTTP server through the XMLHttpRequest object of the browser or through JSONP. The $http service is a function that receives a parameter-a configuration object-for generating an HTTP request and returning promise.

$http ({     method: ' GET ',     url: '/url '}). Then (function Successcallback (response) {     //This callback'll be Called asynchronously     //When the response is available}, function Errorcallback (response) {     //called Asynchrono usly If an error occurs     //or server returns response with an error status.});

Ps: The properties of the Response object: data (the response body used to transform the function transformation), status (HTTP status code for the response), header (), config (the configuration object used to generate the request), StatusText (HTTP status text for the response), Xhrstatus ()

Shortcuts can also be used: ($http (config); )

$http. Get ('/url ', config). Then (Successcallback, Errorcallback); $http. Post ('/url ', data,config). Then ( Successcallback, Errorcallback); $http. Head (Url,[config]); $http. put (Url,data,[config]); $http. Delete (Url,[config] ); $http. JSONP (Url,[config]), $http. Patch (Url,data,[config]);

$http service will automatically add specific HTTP headers for all requests, which can be accessed by accessing the configuration object that currently contains this default configuration. To add or overwrite these default values, simply add or remove properties from these configuration objects.

To add a caption for an HTTP method other than post or put, simply add a new object with the lower HTTP method name as the keyword, such as $httpprovider.defaults.headers.get = {' My-header ': ' Value '}

The default value can also be set at run time through the object in the same way as:

Module.run (function ($http) {    $http. defaults.headers.common.Authorization = ' Basic ymvlcdpib29w ';});

You can provide a property in the Config object passed at headers invocation, overriding the default values and not changing them globally.

To display delete $httpprovider.defaults.headers headers that are automatically added based on each request, use the Headers property to set the desired caption to undefined:

var req = {     method: ' POST ',     URL: ' http://example.com ',     headers:{         ' content-type ': Undefined     },     data:{test: ' Test '}} $http (req). Then (function () {...},function () {...});

The ps:$ prefix is used to indicate that the built-in service is ANGULARJS.

Example: by obtaining data from a JSON file for page rendering, the files involved are: index2.html, App.module.js, phone-list.template.html, Phone-list.component1.js, Phones.json

Index2.html:

<! DOCTYPE html> 

App.module.js:

Used to introduce the module file to be used//define a Phonecatapp module var phonecatapp = angular.module (' Phonecatapp ', []); Define a phonelist module var phonelist = angular.module (' phonelist ', []);

Phone-list.template.html:

<div class= "Container-fluid" > <div class= "Row" > <div class= "col-md-2" > <!--Si Debar content--> <p> Search: <input ng-model= "$ctrl. Query"/> </                     P> <p> Sort by: <select ng-model= "$ctrl. Orderprop" > <option value= "name" >Alphabetical</option> <option value= "age" >newest</o ption> </select> </p> </div> <div class= "col-md-10"             ; <ul class= "Phones" > <li ng-repeat= "Phone in $ctrl. Phones |                     Filter: $ctrl. Query |orderby: $ctrl. Orderprop "> <span>{{phone.name}}</span> <p>{{phone.snippet}}</p> <p>{{phone.age}}</p> &LT;/LI&G             T </ul> </div>    </div> </div> 

Phone-list.component1.js:

Angular.module (' phonelist '). Component (' Phonelist ', {     templateurl: ' phone-list/phone-list.template.html ',     controller:function Phonelistcontroller ($http) {         var = this;         Self.orderprop = ' age ';         $http. Get (' Phones/phones.json '). Then (function (response) {             self.phones = response.data;         });}     );

Phones.json:

[   {     "age": +,     "id": "Motorola-defy-with-motoblur",     "name": "Motorola defy\u2122 with Motoblur\ u2122 ",     " snippet ":" Is your ready for the everything life throws your The "   },   {     " age ":"     ID ":" Sotorola-defy-with-motoblur ",     " name ":" Aotorola defy\u2122 with motoblur\u2122 ",     " snippet ":" hi! Is your ready for everything life throws your? "   

Example: Get data from a JSON file rendered to a table, where the files involved are: mytableindex.html file, app.module.js file, mytable-list.template.html file, Mytable.component.js file, Tables.json file

Mytableindex.html:

<! DOCTYPE html> 

App.module.js:

Used to introduce the module file to be used//define a Phonecatapp module var phonecatapp = angular.module (' Phonecatapp ', []); Define a phonelist module var phonelist = angular.module (' phonelist ', []); Define a tablelist module var tablelist = angular.module (' Tablelist ', []);

Mytable-list.template.html:

<div>     <table>         <caption> Information list </caption>         <tr>             <th> serial </th >             <th> company </th>             <th> Contact </th>             <th> phone </th>         </tr>         <TR ng-repeat= "table in $ctrl. tables1" >             <!--$ctrl. Tables1 the model--> <td>{{obtained in the specified template JS file             table.numx}}</td>             <td>{{table.companyx}}</td>             <td>{{table.contactx}}</td >             <td>{{table.phonex}}</td>         </tr>     </table> </div> <!-- The CSS style of the template can be written in the Style tab of the main HTML file, or an external CSS file is introduced in the main HTML file--

Mytable.component.js:

Angular.module (' tablelist '). Component (' Tablelist ', {     //Here's Angular.module (' Tablelist ') You can also define tablelist components directly with the modules defined in the App.module.js file Tablelist     //On the tablelist template     templateurl: ' phone-list/ Mytable-list.template.html ',     //The URL of the template file used by the component     controller:function Mytablelistcontroller ($http) {         // The controller here is bound to the component tablelist, so the NG directive binding template is no longer required in the template         var self = this;         Self.orderprop = ' numx ';         $http. Get (' Phones/tables.json '). Then (function (response) {             self.tables1 = response.data;  Tables can be understood as the variable name specified by itself, referring to the model, the data in the JSON file         });     } });

Or:

Angular.module (' tablelist '). Component (' Tablelist ', {     //Here's Angular.module (' Tablelist ') You can also define tablelist components directly with the modules defined in the App.module.js file Tablelist     //On the tablelist template     templateurl: ' phone-list/ Mytable-list.template.html ',     //The URL of the template file used by the component     controller:function Mytablelistcontroller ($http) {         // The controller here is bound to the component tablelist, so the NG directive binding template is no longer required in the template         var self = this;         $http ({             method: ' GET ',             URL: ' Phones/tables.json '         }). Then (function Successcallback (response) {             // This callback'll be called asynchronously             //If the response is available self.tables1             = response.data;
   
    }, function Errorcallback (response) {             //called asynchronously if an error occurs             //or server returns response With an error status.             return response.data;         });     });
   

Tables.json:

[   {     "numx": "1",     "Companyx": "Maker",     "Contactx": "Zhajd",     "Phonex": "17878372837"   },   { "     numx": "2", "     Companyx": "Maker Xinxi",     "Contactx": "ZSKD",     "Phonex": "17879072837"   },   { "     numx": "3", "     Companyx": "Maker Keji",     "Contactx": "SHDJCD",     "Phonex": "17870902837"   },   {     "numx": "4",     "Companyx": "Maker GS",     "Contactx": "Djldd",     "Phonex": "17878372837"   },   {     "numx": "5",     "Companyx": "Chuangjiang",     "Contactx": "LDOs",     "Phonex": "17877896837"   },   {     "numx": "6",     "Companyx": "chjdkj",     "Contactx": "Zdljd",     "Phonex": "17878567837 "   

Example: rendering data into a table

<! DOCTYPE html> 

Routing:

Components allow us to combine controllers and templates in a modular, testable way, we will use components for routing, and each route will be associated with a component that will be responsible for providing view templates and controllers.

Angular-route.js: Defines the Angularjs Ngroute module, which provides us with a route.

App.config.js: Configure the main module provided to us.

Phone-detail.module.js: Defines a new module that contains the Phonedetail component.

Phone-detail.component.js: Defines a virtual phonedetail component.

Dependency Injection:

Dependency injection is the core of angularjs and needs to know how it works!

When the application boots, Angularjs creates an injector that is used to find and inject all the services required by the application. Syringes perform only the following steps: Load the module definitions that you specify in the application, register all providers defined in these modules, and, when required to do so, instantiate the service and its dependencies as parameters to the injectable function through its provider. Providers are objects that provide (create) service instances and expose configuration APIs that can be used to control the creation and runtime behavior of services. In the case of the $route service, $routeProvider exposes APIs that allow you to define routes for your application.

Provider ($provide): The $provice service is responsible for telling angular how to create new injectable things called services, that is, the $provide service tells angular how to create a service. The service is defined by the so-called provider, which is the $provide created when used. The provider $provide is defined by the service provider method, $provide injected into the application's config function for service.

Mymod.config (function ($provide) {     $provide. Provider (' greeting ', function () {this         . $get = function () {             return function (name) {                 alert ("Hello" + name);};});     

PS: This defines a new provider named greeting as a service, we can inject a variable named greeting can be injected into any injectable function, such as a controller, angular will call the provider's $get function to return a new service instance. In this case, the thing to inject is a function based on the name parameter and the alert message. We can use this:

Mymod.controller ("Maincontroller", function ($scope, greeting) {     $scope. OnClick = function () {         greeting ("Ford Prefect ");     } })

Service, factory, and value are just shortcuts to defining the parts of the provider, i.e. they provide a way to define the provider without having to enter everything:

Mymod.config (function ($provide) {     $provide. Factory (' greeting ', function () {         return function (name)             { Alert ("Hello," + name);});     

The greeting service always returns the same functionality, so you can use value to define:

Mymod.config (function ($provide) {     $provide. Value (' Greeting ', function (name) {         alert ("Hello," + name);})     ;

var mymod = angular.module (' MyModule ', []);  Mymod.provider (' greeting ',...); Mymod.factory (' greeting ',...); Mymod.service (' greeting ',...); Mymod.value (' greeting ',...); Mymod.provider (' greeting ', function () {this     . $get = function () {         return function (name) {             alert ("Hello," + name);};     }; });  
Mymod.factory (' greeting ', function () { return function (name) { alert ("Hello," + name);}; });
Mymod.service (' greeting ', function () { return function (name) { alert ("Hello," + name);}; });
Mymod.value (' greeting ', function (name) { alert ("Hello," + name);});

Syringe ($injector): Responsible for the actual creation of our service instance using the code $provide we provide. With $injector, you can invoke the defined service instance using the service get name. Syringes are also responsible for injecting service into the function. Each ANGULARJS application has a $injector that is created when the application starts and can be injected into any injectable function by injecting $injector.

Once you have $injector, you can get an instance of a defined service by invoking the Get method of the service

var greeting = $injector. Get (' greeting '); Greeting (' Ford prefect ');

The syringe is also responsible for injecting the service into the function:

var myFunction = function (greeting) {     greeting (' Ford prefect ');}; $injector. Invoke (MyFunction);

Configure the provider:

The provider allows a large number of configurations. When you create a service from a shortcut provided by provider or ANGULARJS, you create a provider that defines how the service was created. These providers can be injected into the config section of your application for easy interaction.

Angular run your program there are two main stages: config, Run;config stage can be set as needed for any provider, this is the place to set instructions, controllers, filters, etc., the run phase is angular actually compile the DOM and launch the application. You can use the Mymod.config and Mymod.run functions to add additional code that runs in these phases. In the config phase, only the supplier can inject.

Controller ($controller): You can inject something into the controller, but you cannot inject the controller into the event.

Filter and instructions (Directive):

To register the core module as a dependency of the primary Phonecatapp module:

Angular.module (' Phonecatapp ', [... ' Core ', ...]);

PS: May be a little messy, please forgive me. The so-called good memory is not as bad as writing, this is the choice to write the original intention of the blog, I hope that through the collation can let oneself deeper understanding, later not clear where can also come back to see. At the same time, in this public place, but also hope to give some people a little bit of reference, at least I get a lot of online. In addition, it is also expected to describe the inappropriate places that there are small partners can point out and then improve and progress. (8-17)

Reference & Thanks: https://docs.angularjs.org

Angularjs Learning Notes-$http, data rendering to tables, routing, dependency injection, provider

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.