[Reprint] AngularJS getting started tutorial 04: two-way binding, angularjs getting started tutorial

Source: Internet
Author: User

[Reprint] AngularJS getting started tutorial 04: two-way binding, angularjs getting started tutorial

In this step, you will add a feature that allows users to control the display sequence of the mobile phone list. Dynamic sorting can be achieved by adding a new model attribute, integrating it with the iterator, and then binding data to complete the rest.

Reset the working directory:

git checkout -f step-4

 

In addition to the search box, you should find that your application has a down menu, which allows you to control the telephone order.

The most important differences between step 3 and Step 4 are listed below. You can see the complete difference in GitHub.

Template

App/index.html

Search: <input ng-model="query">Sort by:<select ng-model="orderProp">  <option value="name">Alphabetical</option>  <option value="age">Newest</option></select><ul class="phones">  <li ng-repeat="phone in phones | filter:query | orderBy:orderProp">    {{phone.name}}    <p>{{phone.snippet}}</p>  </li></ul>

 

InIndex.htmlMade the following changes:

  • First, we addorderPropOf<select>Label, so that our users can select the two sorting methods we provide.
  • ThenfilterAdd an orderBy filter next to the filter to process the data entering the iterator.orderByThe filter uses an array as the input, copies a copy, sorts the copies, and then outputs them to the iterator.

AngularJSselectElement andorderPropTwo-way binding is created between models. Then,orderPropWill be usedorderByThe input of the filter.

As we mentioned in step 3 when discussing data binding and iterator, no matter when the data model changes (for example, the user selects a different order from the drop-down menu ), the Data Binding of AngularJS will automatically update the view. No clumsy DOM operations!

Controller

App/js/controllers. js:

function PhoneListCtrl($scope) {  $scope.phones = [    {"name": "Nexus S",     "snippet": "Fast just got faster with Nexus S.",     "age": 0},    {"name": "Motorola XOOM™ with Wi-Fi",     "snippet": "The Next, Next Generation tablet.",     "age": 1},    {"name": "MOTOROLA XOOM™",     "snippet": "The Next, Next Generation tablet.",     "age": 2}  ];  $scope.orderProp = 'age';}

 

  • We modifiedphonesModel-cell phone array-addsageAttribute. We willageTo sort mobile phones.
  • We added a line of authorization to the Controller code.orderPropThe default value isage. If we do not set the default value, this model will remain uninitialized until our users select an order from the drop-down menu.

    Now let's talk about two-way data binding. Note that when the application is loaded in the browser, "Newest" is selected from the drop-down menu. This is because we putorderPropSet to 'age '. Therefore, binding takes effect in the direction from our model to the user interface-that is, binding data from the model to the view. Now, when you select "Alphabetically" from the drop-down menu, the data model will be updated at the same time, and the cell phone list array will be re-ordered. In this case, data binding takes effect in another direction-from the view to the model.

Test

Our changes can be verified through a unit test or an end-to-end test. Let's first take a look at unit testing:

Test/unit/controllersSpec. js:

describe('PhoneCat controllers', function() {  describe('PhoneListCtrl', function(){    var scope, ctrl;    beforeEach(function() {      scope = {},      ctrl = new PhoneListCtrl(scope);    });    it('should create "phones" model with 3 phones', function() {      expect(scope.phones.length).toBe(3);    });    it('should set the default value of orderProp model', function() {      expect(scope.orderProp).toBe('age');    });  });});

 

The unit test now verifies that the default value is correctly set.

We use the Jasmine interfacePhoneListCtrlThe Controller extractsbeforeEachBlock, this block will be owned by all parent BlocksdescribeAll tests in.

Run these unit tests../scripts/test.shScript, you should see the following output (Note:You need to open http: // localhost: 9876 in the browser and enter the strict mode, the test will run !) :

Chrome: Runner reset...Total 2 tests (Passed: 2; Fails: 0; Errors: 0) (3.00 ms)  Chrome 19.0.1084.36 Mac OS: Run 2 tests (Passed: 2; Fails: 0; Errors 0) (3.00 ms)

Now we focus on end-to-end testing.

Test/e2e/scenarios. js:

...    it('should be possible to control phone order via the drop down select box',        function() {      //let's narrow the dataset to make the test assertions shorter      input('query').enter('tablet');      expect(repeater('.phones li', 'Phone List').column('phone.name')).          toEqual(["Motorola XOOM\u2122 with Wi-Fi",                   "MOTOROLA XOOM\u2122"]);      select('orderProp').option('Alphabetical');      expect(repeater('.phones li', 'Phone List').column('phone.name')).          toEqual(["MOTOROLA XOOM\u2122",                   "Motorola XOOM\u2122 with Wi-Fi"]);    });...

 

The end-to-end test verifies that the option box sorting mechanism is correct.

You can refresh your browser and run the end-to-end test again, or you can run it on AngularJS server.

Exercise
  • InPhoneListCtrlIn the controller, SetorderPropDelete the statement. You will see that AngularJS will temporarily AddBlankAnd the default sorting order (that is, unordered ).
  • Inindex.htmlAdd a '{orderProp} binding in the template to display its value in real time.
Summary

Now you have provided the search function for your application and completed the test. Step 5: we will learn about AngularJS services and how AngularJS uses dependency injection.


What is the core idea of AngularJS? What types of applications are applicable? How to get started?

The type idea is MVC, that is, Model-> Controler-> View. Model, control the view through the Controller

Replace the traditional data object mode with the direct operation data model and then change the page DOM mode.

Single-page APP for highly complex object models


Related Article

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.