[英]A Directive to link a controller to a form submit. What am I missing?
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. 所以这是场景:我在整个页面中有多个新闻稿表单,我需要所有这些表单执行相同的操作:使用一些数据发出AJAX请求,并在请求完成时使用警报向用户返回一条消息。 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. 它按预期工作,但是,你可以看到我正在使用jQuery ajax方法。 I wanted to use Angular built-in http, but I can't inject it for some reason. 我想使用Angular内置的http,但由于某些原因我无法注入它。 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? 我还尝试制作一个控制器来处理ajax请求但没有成功......任何人都知道如何改进这段代码? Thanks. 谢谢。
You need to inject the $http
into the directive so it can be used. 您需要将$http
注入指令,以便可以使用它。
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
. 我会说,一个指令可以处理这个问题,但由于你并没有真正做DOM操作,你可以使用ngClick
和ngSubmit
在控制器中完成所有这些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. 指令被设计为可重用的新HTML元素,提供功能,动画,监听器等。它们执行DOM操作和/或监听事件并调用控制器中的特定功能。
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. 如果它在同一页面上处理多个表单,那么指令就可以工作,或者您可以修改控制器来处理表单,无论哪种方式都有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.