To create a directive that automatically saves form data at intervals in AngularJS, utilize $interval within a custom directive to monitor the form model and initiate a save function consistently.
AngularJS Auto-Save Directive
1. Directive Code
app.directive('autoSave', function($interval) {
return {
restrict: 'A',
scope: {
model: '=autoSave',
onSave: '&'
},
link: function(scope) {
var intervalPromise = $interval(function() {
if (scope.model) {
scope.onSave({ data: angular.copy(scope.model) });
}
}, 5000); // auto-save every 5 seconds
scope.$on('$destroy', function() {
$interval.cancel(intervalPromise);
});
}
};
});
2. Usage in HTML
<form name="userForm">
<input type="text" ng-model="user.name" placeholder="Name" />
<input type="email" ng-model="user.email" placeholder="Email" />
<!-- Auto-save directive usage -->
<div auto-save="user" on-save="saveUser(data)"></div>
</form>
3. Controller Function
$scope.user = {};
$scope.saveUser = function(data) {
console.log("Auto-saving data:", data);
// You can replace this with an API call
};