Home > Web Front-end > JS Tutorial > body text

angularjs implements interactive sharing with the server_AngularJS

WBOY
Release: 2016-05-16 16:43:14
Original
1414 people have browsed it

Real applications need to interact with real servers. Mobile applications and the emerging Chrome desktop applications may be exceptions, but for all other applications, whether you want to persist data to the cloud or need to communicate with other For real-time interaction, users need to let the application interact with the server.

To achieve this, Angular provides a service called $http. It provides an extensible list of abstract methods to make interacting with the server easier. It supports HTTP, JSONP and CORS methods. It also includes security support to avoid JSON format vulnerabilities and XSRF. It allows you to easily transform request and response data and even implements simple caching.

For example, we intend to let the shopping site obtain product information from the server instead of obtaining fake data from the memory. How to write server-side code is beyond the scope of this book, so let's just imagine that we have created a server that, when querying the /products path, returns a list of products in JSON format.

An example of the response returned is as follows:

[

 {

  "id": 0,

  "title": "Paint pots",

  "description": "Pots full of paint",

  "price": 3.95

 },

 {

  "id": 1,

  "title": "Polka dots",

  "description": "Dots with that polka groove",

  "price": 12.95

 },

 {

  "id": 2,

  "title": "Pebbles",

  "description": "Just little rocks, really",

  "price": 6.95

 }

 ...etc...

]

Copy after login

We can write query code like this:

function ShoppingController($scope, $http) {

 $http.get('/products').success(function(data, status, headers, config) {

  $scope.items = data;

 });

}
Copy after login

Then use it in your template like this:

<body ng-controller="ShoppingController">

  <h1>Shop!</h1>

  <table>

   <tr ng-repeat="item in items">

    <td>{{item.title}}</td>

    <td>{{item.description}}</td>

    <td>{{item.price | currency}}</td>

   </tr>

  </table>

 </div>

</body>
Copy after login

As we said before, in the long run, it will be beneficial for us to have a service proxy the work of interacting with the server. This service can be shared by multiple controllers.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!