Let's set the scene: There are multiple newsletter forms scattered across a webpage, all needing to perform the same action. This action involves making an AJAX request with certain data and displaying a message using an alert once the request is complete. Currently, the implementation looks like this:
var myApp = angular.module('myApp', []);
myApp.directive('form-newsletter', [function() {
return {
restrict: 'C',
link : function($scope, elem) {
$scope.data = { }
var $el = elem.find('button[type=submit]');
$el.on('click' , function(){
if (! $scope.data.email ){
alert("Please, fill in the e-mail");
return false;
}
if ( $(this).val().length > 0 ){
$scope.data.gender = $(this).val();
}
var data = $scope.data;
$.ajax({
url: '/newsletter/join',
type: 'get',
dataType: 'json',
data: data,
success: function(data) {
if (data.validation == true) {
alert('Thank you for joining our mailing list.');
} else {
alert(data.error);
}
}
})
return false;
});
}
}
}]);
The current solution works fine, but there's room for improvement. Ideally, Angular's built-in http module would be used instead of jQuery ajax, but encountering issues when trying to inject it. There have been attempts to create a controller to handle the AJAX request, but without success so far. Any suggestions on how to enhance this code? Your help is appreciated.