SoFunction
Updated on 2025-04-08

AngularJS Introductory Tutorial: Detailed explanation of event processor

In this step, you will make the mobile phone picture clickable on the mobile phone details page.

Please reset the working directory:

git checkout -f step-10

The mobile phone details view shows a large picture of the current phone, as well as a few smaller thumbnails. It would be even better if the user clicks on the thumbnail and can replace the big one with himself. Now let's see how to implement it with AngularJS.

The most important differences between Step 9 and Step 10 are listed below. You can see the complete difference in GitHub.

Controller

app/js/

...
function PhoneDetailCtrl($scope, $routeParams, $http) {
 $('phones/' + $ + '.json').success(function(data) {
 $ = data;
 $ = [0];
 });

 $ = function(imageUrl) {
 $ = imageUrl;
 }
}

//PhoneDetailCtrl.$inject = ['$scope', '$routeParams', '$http'];

In the PhoneDetailCtrl controller, we create the mainImageUrl model property and set its default value to the URL of the first mobile image.

template

app/partials/

<img ng-src="{{mainImageUrl}}" class="phone">

...

<ul class="phone-thumbs">
 <li ng-repeat="img in ">
 <img ng-src="{{img}}" ng-click="setImage(img)">
 </li>
</ul>
...

We bind the ngSrc directive of the large image to the mainImageUrl property.

At the same time, we register a ngClick processor to the thumbnail. When a user clicks on any of the thumbnails, the processor will use the setImage event handling function to set the mainImageUrl property to the URL of the selected thumbnail.

test

To verify this new feature, we added two end-to-end tests. A verification main image is set to the first mobile image by default. The second test clicks on several thumbnails and verifys that the main image changes reasonably.

test/e2e/

...
 describe('Phone detail view', function() {

...

 it('should display the first phone image as the main phone image', function() {
  expect(element('').attr('src')).toBe('img/phones/nexus-s.');
 });

 it('should swap main image if a thumbnail image is clicked on', function() {
  element('.phone-thumbs li:nth-child(3) img').click();
  expect(element('').attr('src')).toBe('img/phones/nexus-s.');

  element('.phone-thumbs li:nth-child(1) img').click();
  expect(element('').attr('src')).toBe('img/phones/nexus-s.');
 });
 });
});

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

practise

Add a new controller method to PhoneDetailCtrl:

 $ = function(name) {
  alert('Hello ' + (name || 'world') + '!');
 }

And add:

 <button ng-click="hello('Elmo')">Hello</button>

arrivetemplate.

Summarize

Now that the image browser is ready, we are ready for step 11 (the last step!), we will learn to get data in a more elegant way.

The above is the information sorted out of the AngularJS event processor. We will continue to add it later. Thank you for your support for this site!