Seven steps from Angular.js rookie to expert (3): Data binding and Ajax

Source: Internet
Author: User

This is the third of the "AngularJS-seven steps from rookie to expert" series.

In the first article, we showed how to start building a ANGULARAJS application. In the second chapter we discuss the scope and $scope functions.

Through this entire series of tutorials, we will develop an audio player for NPR (National Public Radio), which will display the latest stories that are now aired on the Morning edition program and play them in our browser. Complete version of the demo can be seen here.

Part III Data binding

By binding a text input box to the Person.name attribute, you can make our application a little more interesting. This step establishes a two-way binding between the text input box and the page.

In this context "bidirectional" means that if the view changes the attribute value, the model will "see" the Change, and if the model changes the attribute value, the view will also "see" the change. Angular.js automatically set up this mechanism for you. If you are curious about how this is done, see our post-release article, which delves into the workings of digest_loop.

To create this binding, we use the Ng-model Directive property on the text input box, like this:

  1. <div ng-controller="Mycontroller">
  2. <input type="text" ng-model="Person.name" placeholder="Enter your name" />
  3. <h5>hello {{person.name}}</h5>
  4. </div>

Now that we've set up a data binding (yes, it's so easy), let's see how the View changes model:

Try:

When you type in a text box, the following name is automatically changed, which shows the direction of our data binding: from view to model. We can also change the model in our (client) background to see how this change is automatically reflected in the front end. To demonstrate this process, let's write a timer function in the   MyController  model,  update   $scope   a data. In the following code, we will create this timer function, which will be timed every second (like a clock) and update the clock variable data on   $scope  :

    1. App.controller (' Mycontroller ', function ($scope) {$Scope.person = {name: "Ari Lerner"};  var updateclock = function () {$scope.clock = new Date ();  };  var timer = setinterval (function () {$scope. $apply (Updateclock);  }, 1000); Updateclock ();});

As you can see, when we change the data of the Modelclock variable, view automatically updates to reflect this change. With curly braces we can simply make the value of the clock variable appear in the view:

    1. <div ng-controller="Mycontroller">
    2. <h5>{{Clock}}</h5>
    3. </div>

Please see:

{{Clock}}

Interaction

We've bound the data to the text input box. Note that data binding is not limited to data, and we can also use bindings to invoke functions in $scope (as mentioned earlier).

For a button, link, or any other DOM element, we can use another directive property to implement the binding: Ng-click. This ng-click instruction binds the DOM element's mouse click event (that is, the MouseDown browser event) to a method that is called when the browser triggers a click event on the DOM element. Similar to the previous example, the code for this binding is as follows:

  1. <div ng-controller="Democontroller">
  2. <h4>the simplest adding machine ever</h4>
  3. <button ng-click="Add (1)" class="button">add</button>
  4. <button ng-click="Subtract (1)" class="button">subtract</ Button>
  5. <h4>current Count: {{counter}}</h4>
  6. </div>

Both buttons and links are bound to all $scope objects of the controller that contain their DOM elements, and when they are clicked by the mouse, angular calls the appropriate method. Note that when we tell angular what method to invoke, we write the method name into the quoted string.

    1. App.controller (' Democontroller ', function ($scope) {
    2. $scope.counter = 0;
    3. $Scope.add = function (amount) {$scope. counter + = amount;};
    4. $scope.subtract = function (amount) {$scope. Counter- = amount;};
    5. });

Please see:

Data binding and Ajax in MyApp

Interaction

In the previous example, we have just learned the data binding to a button on the view, and have bound the play method to the Playercontroller (again, the Stop button is bound to the Stop method).

Ajax

In the previous tutorial, we quoted a local audio file, which gave us a static NPR file instead of a dynamic NPR feed. In our NPR app, we'll use $http to populate a list of news files that we can play. Angular.js native support Ajax, so we have the ability to send requests back and forth to one or more servers. This capability is critical to the client-side application that we're creating, because it requires communication with the server to get and update the data. Angular.js supports Ajax through a service (which we'll discuss later in this section), a service called $http service. All Angular.js core Services are prefixed with $, which we have seen in the previous $scope service. This $http service is extremely flexible and gives us many ways to invoke Ajax services. To ensure that this tutorial is easy to understand, we focus on the simplest way. In later chapters, we'll go into more detail about $http services. Before going into too much detail, let's start by creating a request with the $http service:

    1. $http ({method: ' JSONP ', url: ' Http://api.openbeerdatabase.com/v1/beers.json?  callback=Json_callback '}). Success (function (data, status, headers, config) {//data contains the response//status is the HTTP status//headers are the header Getter function//config is the object this was used to create the HTTP req Uest}). Error (Function (data, status, headers, config) {});

Try:

$http Service is one of the core services of Angular.js, which helps us communicate with remote HTTP services through XMLHttpRequest objects or JSONP.

Note that, as in the example above, with the following string Callback=json_callback intact, Angular.js will be responsible for handling JSONP requests for you, replacing json_callback with a suitable callback function.

The $http service is a function that takes a setting object that specifies how to create an HTTP request; it returns a promise (* Reference JavaScript Asynchronous Programming's Promise mode), which provides two methods: The Success method and the error method.

To get a list of playable audio files, let's send a request to the NPR API. First, you need to reverse the NPR registration to get an API key. Go to their website http://www.npr.org/templates/reg/. (the author uses angular.js to make an IFRAME-loaded NPR registration form, either, or go directly to the original English text).

Make a note of your API key and we'll use it right away. Now we're going to set up our Playcontroller to invoke the $http service and retrieve the audio file.

As we've just done, let's call the $http service to create a request, this time to get all the audio files. We want this service to start when the controller is instantiated, so we just need to put this method directly in the Controller function (this function is called when the controller is created), like this:

  1. var apiKey = ' Your_key ',
  2. Nprurl = ' Http://api.npr.org/query?id=61&fields=relatedLink,title,byline,text,audio,image,pullQuote, All&output=json ';
  3. App.controller (' Playercontroller ', function ($scope, $http) {
  4. Hidden our previous section ' s content
  5. Construct our HTTP request
  6. $http ({
  7. Method: ' JSONP ',
  8. Url:nprurl + ' &apikey=' + ApiKey + ' &callback=json_callback '
  9. }). Success (function (data, status) {
  10. Now we have a list of the stories (data.list.story)
  11. In the data object that the NPR API
  12. Returns in JSON, looks like:
  13. Data: {"List": {
  14. "Title": ...
  15. "Story": [
  16. {"id": ...
  17. "Title": ...
  18. }). Error (Function (data, status) {
  19. Some Error occurred
  20. });
  21. });

Now we have a list of audio files in the data of the success function. In the success callback function, the list is stored in the $scope object so that we simply bind it to the $scope object:

    1. From above
    2. }). Success (function (data, status) {
    3. Store the list of stories on the scope
    4. From the NPR API response object (described above)
    5. $scope.programs = data.list.story;
    6. }). Error (Function (data, status) {
    7. Some Error occurred

Now, just as you can access the programs in view, we'll be able to access this data in view. You see, one of the benefits of using angular.js is that when the commit mode returns to a successful outcome, Angular.js automatically fills in your view with that result.

    1. <div ng-controller="Playercontroller">
    2. {{Programs}}
    3. </div>

Try:

In the next chapter, we'll discuss how to show this data object meaningfully in our view, using some of the angular.js's own instructions (and a little bit more).

The official code base for this series can be downloaded from github:

Https://github.com/auser/ng-newsletter-beginner-series.

To save this code base locally, make sure you have installed Git,clone this codebase and check out the PART3 branch:

    1. git clone https://github.com/auser/ng-newsletter-beginner-series.git
    2. Git checkout-b part3

Original link: http://www.ng-newsletter.com/posts/beginner2expert-data-binding.html

Link: http://blog.jobbole.com/48780/

Seven steps from Angular.js rookie to expert (3): Data binding and Ajax

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.