ANGULARJS Introduction 4: Multi-view, event binding, $resource Services explained

Source: Internet
Author: User

Last lesson, you know, cell phone detailed template We did not write out, using a placeholder template.

in this lesson, we first implement the phone details view, which is displayed when the user clicks on a phone in the phone list .

To implement the phone detail view, we'll use $http to get the data.

The following JSON object is the phone's detailed information, which we'll display in the phone details view.

{  "additionalfeatures": "Contour Display, near Field Communications (NFC),...",  "Android" : {      "OS": "Android 2.3",      "UI": "Android"  },  ...  " Images ": [      " Img/phones/nexus-s.0.jpg ",      " Img/phones/nexus-s.1.jpg ",      "Img/phones/nexus-s.2.jpg",      "img/phones/nexus-s.3.jpg"  ],  "Storage" : {      "flash": "16384MB",      "Ram": "512MB"  }}

We use the $http service to get data to expand our Phonedetailctrl controller. This works the same way as the previous phone list controller.

function Phonedetailctrl ($scope, $routeParams, $http) {
$http. Get (' phones/' + $routeParams. Phoneid + '. JSON '). Success (function (data) {
$scope. Phone = data;
});
}

The phone-detail.html file has a TBD placeholder that has been replaced by phone details. Notice here that we use Angularjs's {{expression}} tags and ngrepeat to render the data model in the view.

    ...   </li>    <span>additional features</span>    <dd>{{phone.additionalfeatures}}</ Dd>  </li></ul>

Then, we create our own filters in the program.

To create a new filter, we first create a module and phonecatFilters register the custom filter checkmark with the module.

Angular.module (' phonecatfilters ', []). Filter (' Checkmark ', function () {
return function (Input) {
return input? ' \u2713 ': ' \u2718 ';
};
});

Our filter is named Checkmark. Its input is either true or false, and we return two Unicode characters (\u2713 and \u2718) that represent true or false.

Now that our filters are ready, we need to phonecatFilters register our module as a dependency on our main module phonecat .

...
Angular.module (' Phonecat ', [' phonecatfilters ']).
...

The syntax for using filters in the Angularjs template is: {{expression | filter}}

Therefore, we apply the filter to the cell phone details template, which reads:

...     <dl>      <dt>Infrared</dt>      <dd>{{phone.connectivity.infrared | checkmark}}</dd >      <dt>GPS</dt>      <dd>{{phone.connectivity.gps | checkmark}}</dd>    </dl A..

This enables a feature where the phone detail page turns out to show "true" or "false" to indicate whether a phone has a specific feature. Now we use a custom filter to graph those text strings: √ as "true" and X as "false". Also said that, on the phone detail page, the true becomes the √,false becomes x.

Finally, we let the phone picture on the phone details page be clickable.

The phone Details view shows a large picture of the current phone and a few smaller thumbnails. We realize that when the user clicks on the thumbnail image, it can replace the large one with the one that the user clicked.

... function Phonedetailctrl ($scope, $routeParams, $http) {  $http. Get (' phones/' + $routeParams. Phoneid + '. Json '). Success (function(data) {    = data;     = Data.images[0];   function (IMAGEURL) {    = imageUrl;  }}

In the Phonedetailctrl controller, we created the Mainimageurl model property and set its default value to the URL of the first phone picture.

... <ul class= "Phone-thumbs" >  <li ng-repeat= "img in phone.images" >      </li></ul>

We bind the instruction of the big picture ngSrc to the mainImageUrl attribute.

At the same time we register a ngclick processor to the thumbnail. When a user clicks on any of the thumbnails, the processor uses the SetImage event handler to set the Mainimageurl property to the URL of the selected thumbnail image.

This makes it easy to achieve the above requirements.

The last improvement to our application is the way you get the data. We can send XHR requests in a much simpler way without having to care about the underlying $http service.

Angular.module (' phonecatservices ', [' Ngresource ']).    Factory (' Phone ', function($resource) {      return $resource (' phones/:p Honeid.json ', {}, {        query: {method : ' GET ', Params:{phoneid: ' Phones '}, Isarray:true}      })        ;

We used the module's API to register a custom service phone through its factory method. We pass in the service's name phone and factory function. Factory functions and controller constructors are similar, and they all depend on the function's argument declaration to rely on the service. The phone service declares that it relies on the $resource service.

We need to load the Angularjs-resource.js file on the page, which contains the ngResource modules and the $resource services in them:

...
<script src= "Lib/angular/angular-resource.js" ></script>
...

$resource Service, you can create a restful client with just a few lines of code. Our application uses this client instead of the underlying $http service. Angularjs $resource is more suitable for interacting with restful data sources than $http.

Then we need to phonecatServices add to phonecat the dependency array.

...
Angular.module (' Phonecat ', [' phonecatfilters ', ' phonecatservices ']).
...

By refactoring the underlying $http service and placing it in a new service phone, we can greatly simplify the sub-controllers (Phonelistctrl and Phonedetailctrl).

... function Phonelistctrl ($scope, Phone) {  $scope. Phones = phone.query ();  $scope. Orderprop = ' age ';} Phonelistctrl. $inject = [' $scope ', ' phone '];function Phonedetailctrl ($scope, $routeParams, Phone) {  $ Scope.phone = Phone.get ({phoneid: $routeParams. Phoneid}, function(phone) {$scope. Mainimageurl = phone.images[0 ]; }); $scope. setimage = function(IMAGEURL) {$scope. Mainimageurl = ImageUrl;}} Phonedetailctrl. $inject = [' $scope ', ' $routeParams ', ' Phone '];       

Notice that in the Phonelistctrl we put:

$http. Get (' Phones/phones.json '). Success (function (data) {
$scope. phones = data;
});

Replaced by:

$scope. Phones = Phone.query ();

We use this simple statement to query all the phones.

Another very important note is that, in the above code, when the Phonelistctrl controller calls the phone service method, we do not pass any callback functions. Although this seems to be a synchronous return, it is not at all. The synchronization returned is a "future"-an object that populates the data when the XHR response is completed. Given the ANGULARJS data binding, we can use the future and bind it to our template. Then, when the data arrives, our view is automatically updated.

But sometimes, relying solely on future objects and data binding is not enough to meet our needs, so in these cases we need to add a callback function to handle the server's response. The Phonedetailctrl controller is an explanation by setting Mainimageurl in a callback function.

Through the four introductory lectures on angular.js, I believe that we all angular have a preliminary understanding, and then we will explain in depth angular.js.

Come on!

ANGULARJS Introduction 4: Multi-view, event binding, $resource Services explained

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.