Episode 14 of 25
The ng-submit Directive
Learn how to handle form submissions with ng-submit.
The ng-submit directive lets you handle form submissions and prevent the default browser behaviour.
Basic ng-submit
<form ng-submit="submitForm()">
<input ng-model="username" placeholder="Username" required>
<input ng-model="email" placeholder="Email" required>
<button type="submit">Submit</button>
</form>
app.controller('FormCtrl', function($scope) {
$scope.username = '';
$scope.email = '';
$scope.submitForm = function() {
console.log('Username:', $scope.username);
console.log('Email:', $scope.email);
alert('Form submitted!');
};
});
Building a Todo App
app.controller('TodoCtrl', function($scope) {
$scope.todos = [];
$scope.addTodo = function() {
$scope.todos.push({
text: $scope.newTodo,
done: false
});
$scope.newTodo = '';
};
});
<div ng-controller="TodoCtrl">
<form ng-submit="addTodo()">
<input ng-model="newTodo" placeholder="Add task..." required>
<button type="submit">Add</button>
</form>
<ul>
<li ng-repeat="todo in todos">
<input type="checkbox" ng-model="todo.done">
<span ng-class="{'line-through': todo.done}">{{ todo.text }}</span>
</li>
</ul>
</div>
ng-submit vs Button ng-click
ng-submit— handles form submission including Enter key pressng-clickon a button — only handles button clicks
Use ng-submit for forms, ng-click for standalone buttons.