Sunday, October 9, 2016

AngularJS - Events

AngularJS has directives which can be used as an event listener to your HTML elements. An AngularJS event will never overwrite an HTML event, rather both the events will be executed. These directives allow us to run AngularJS functions as certain user events. Below is the list of all the directives which can be used as an event listener:
ng-blur
ng-change
ng-click
ng-copy
ng-cut
ng-dblclick
ng-focus
ng-keydown
ng-keypress
ng-keyup
ng-mousedown
ng-mouseenter
ng-mouseleave
ng-mousemove
ng-mouseover
ng-mouseup
ng-paste

Example of using ng-click
Lets say we have a table with different kinds of sports listed which shows number of likes and dis-likes as shown below in the table. When the Like button is clicked it increases the like when Dislike button is clicked it increases the dis-likes. 


var myApp = angular.module('myApp', [])
                                     .controller('myController', function($scope){
                                                var sports= [
                                                       { name: Cricket,  likes: 0, dislikes: 0},
                                                       { name: Football,  likes: 0, dislikes: 0},
                                                       { name: Basketball,  likes: 0, dislikes: 0}
                                                ];    
                                          });
                                                 $scope.sports = sports;

                                                 $scope.incrementLikes=  function(sport){
                                                        sport.likes++;         
                                                 };

                                                 $scope.incrementDislikes=  function(sport){

                                                        sport.dislikes++;         
                                                 };

Using this controller:
     <div ng-controller='myCOntroller'>
              <div>
                       <table>
                             <tr ng-repeat ='sport in sports'>
                                    <td> {{sport.name}}</td>
                                    <td> {{sport.likes}} </td>
                                    <td>{{sport.dislikes}} </td>
                                    <td> <button  value='Like' ng-click='incrementLikes(sport)'/></td>
                                    <td> <button value='Dislike' ng-click='incrementDislikes(sport)' </td>
                       </table>
              </div>                  
    </div>

No comments:

Post a Comment