So here's the scenario: I have multiple newsletter forms throughout a page and I need all of them to execute the same action: Make an AJAX request with some data and, upon request completion, return a message to the user using an alert. So far I have 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;
});
}
}
}]);
It works as expected, but, as you can see I'm using jQuery ajax method. I wanted to use Angular built-in http, but I can't inject it for some reason. I also tried to make a controller to handle the ajax request but had no success... Any one has any idea of how can I improve this piece of code? Thanks.
You need to inject the $http
into the directive so it can be used.
myApp.directive('form-newsletter', ['$http',function($http) {
I will say, a directive can handle this, but since you aren't really doing DOM manipulation, you could probably do all this in the controller fairly easy using ngClick
and ngSubmit
.
Directives are designed to be reusable new HTML elements, providing features, animation, listeners, etc. They do DOM manipulation and/or listen for events and call specific functions in your controller.
If your code is simply handling a form submission, you could probably do it in the controller. If it is handling multiple forms on the same page, then a directive would work, or you could modify your controller to handle the forms as well, either way works.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.