Episode 13 of 25
The ng-click Directive
Learn how to handle click events with ng-click and call controller methods.
The ng-click directive lets you run expressions or call controller methods when an element is clicked.
Basic ng-click
<div ng-app="" ng-init="count=0">
<button ng-click="count = count + 1">Click me</button>
<p>Clicked {{ count }} times</p>
</div>
Calling Controller Methods
app.controller('TodoCtrl', function($scope) {
$scope.todos = [];
$scope.newTodo = '';
$scope.addTodo = function() {
if ($scope.newTodo.trim()) {
$scope.todos.push({
text: $scope.newTodo,
done: false
});
$scope.newTodo = '';
}
};
$scope.removeTodo = function(index) {
$scope.todos.splice(index, 1);
};
$scope.toggleDone = function(todo) {
todo.done = !todo.done;
};
});
<div ng-controller="TodoCtrl">
<input ng-model="newTodo" placeholder="New task">
<button ng-click="addTodo()">Add</button>
<ul>
<li ng-repeat="todo in todos">
<span ng-click="toggleDone(todo)"
ng-class="{'done': todo.done}">
{{ todo.text }}
</span>
<button ng-click="removeTodo($index)">×</button>
</li>
</ul>
</div>
Other Event Directives
<div ng-dblclick="doubleClicked()">Double click me</div>
<div ng-mouseenter="hovered = true">Hover me</div>
<div ng-mouseleave="hovered = false">Leave me</div>
<input ng-change="inputChanged()" ng-model="value">
<input ng-keypress="keyPressed($event)" ng-model="text">