Handling events in AngularJS:-
Let us understand with an example. Here is what we want to do.
Script.js:- In the controller function we have 2 methods to increment likes and dislikes. Both the functions have the technology object that we want to like or dislike as a parameter.
Demo.html : Notice in the html below, we are associating incrementLikes() and incrementDislikes() functions with the respective button. When any of these buttons are clicked, the corresponsing technology object is automatically passed to the function, and the likes or dislikes property is incremented depending on which button is clicked.
Out Put: Run the application and get out put:-
- Display the list of technologies in a table
- Provide the ability to like and dislike a technology
- Increment the likes and dislikes when the respective buttons are clicked
Script.js:- In the controller function we have 2 methods to increment likes and dislikes. Both the functions have the technology object that we want to like or dislike as a parameter.
var app = angular .module("myModule", []) .controller("myController", function ($scope) { var technologies = [ { name: "C#", likes: 0, dislikes: 0 }, { name: "ASP.NET", likes: 0, dislikes: 0 }, { name: "SQL", likes: 0, dislikes: 0 }, { name: "AngularJS", likes: 0, dislikes: 0 }, { name: "MVC", likes: 0, dislikes: 0 } ]; $scope.technologies = technologies; $scope.incrementLikes = function (technology) { technology.likes++; }; $scope.incrementDislikes = function (technology) { technology.dislikes++; }; });
Demo.html : Notice in the html below, we are associating incrementLikes() and incrementDislikes() functions with the respective button. When any of these buttons are clicked, the corresponsing technology object is automatically passed to the function, and the likes or dislikes property is incremented depending on which button is clicked.
Name Likes Dislikes Like/Dislike {{ technology.name }} {{ technology.likes }} {{ technology.dislikes }}
Out Put: Run the application and get out put:-