[100 Days Angularjs] Day 9: Tutorial - 10 - Event Handlers


Day 9 of 100 days with Angular

So i notice that because they still don’t teach the Controller As syntax so i have to inject the global $scope into my controller to public some property from that controller. And about event handler because i have some background with C# so i know that an event handler is just some function that subscribe to some event. And from what i see here it is the same concept.

Controller

app/js/controllers.js:

...
var phonecatControllers = angular.module('phonecatControllers',[]);

phonecatControllers.controller('PhoneDetailCtrl', ['$scope', '$routeParams', '$http',
  function($scope, $routeParams, $http) {
    $http.get('phones/' + $routeParams.phoneId + '.json').success(function(data) {
      $scope.phone = data;
      $scope.mainImageUrl = data.images[0];
    });

    $scope.setImage = function(imageUrl) {
      $scope.mainImageUrl = imageUrl;
    };
  }]);

So here they public the setImage function to the global scope so we can use it in the template.

Template

app/partials/phone-detail.html:

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

And here is where we subscribe that event. So everytime the click event is fired we will run this function with img as an argument. And it will set the current mainImageUrl to that img variable.

Related Posts

[100 Days Angularjs] Day 10: Tutorial - 11,12 REST and Animation

The 9th day of my 100 day challenge with AngularJS

[100 Days Angularjs] Day 8: Tutorial - 9 - Filters

The 8th day of my 100 day challenge with AngularJS