1

I have a simple custom directive with a http post call to a url. When the submit button is clicked it supposed to call the url as custom directive attribute is placed inside the tag.

I checked in chrome console that its not getting called. I am not sure where I went wrong.

Code:

<!DOCTYPE html>
<html ng-app="myApp" >
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script>
            var app = angular.module('myApp',[]);
            app.directive('sendMail', function ($http) {
                return {
                    restrict: 'A',
                    require: 'ngModel',
                    link: function (scope, element, attrs, ngModel) {
                        $http.post('MailSenderServlet.do').success(function (data) {
                        });
                    }
                };
            });
        </script>
        <title>Registration Form</title>
    </head>
    <body ng-controller="MainCtrl">
        <div class="container">
            <h2 class="text-muted">Registration form</h2><br/>
            <div>
                <form name="myForm" action="RegistrationServlet.do" method="POST" novalidate>
                    <div class="form-group has-feedback">
                        <label class="control-label">First name:</label> <input type="text" class="form-control input-sm " name="uname" ng-pattern="/^[a-zA-Z]{3,20}/" ng-model="user.uname" placeholder="First Name" required/>
                        <span style="color:red" ng-show="myForm.uname.$error.pattern">First name cannot be less than 3 letters with no digits</span>
                        <span style="color:red" class="error" ng-if="myForm.$submitted && myForm.uname.$error.required">Please fill field above<br></span>
                        <span style="color:red" class="hide-while-in-focus" ng-show="myForm.uname.$error.unique">Username already exist<br/></span>
                        <span ng-if="myForm.uname.$valid" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
                    </div>
                    <button class="form-control btn btn-success" type="submit" name="submit" ng-model="submit" send-mail ">Submit</button>
                </form>
            </div>            
        </body>
    </html>
3
  • it should call right after directive loads, place a alert(); inside the link function and remove current items inside the link function and you will see the alert(); plnkr.co/edit/VmknY04jPcJDoigaOXxy?p=preview Commented Jun 28, 2015 at 16:52
  • link: function (scope, element, attrs, ngModel) {alert("Hi");} ?? I tried this, I didn't get any alert Commented Jun 28, 2015 at 16:55
  • @kittu: See my answer, you just need a minor tweak.. Commented Jun 28, 2015 at 17:03

3 Answers 3

1

it should call right after directive loads, place a alert(); inside the link function and remove current items inside the link function and you will see the alert();

DEMO

but if you want to call a function right after the button click, you need ng-click directive and a controller function to execute after the click in directive controller or link function.

<button  ng-click="sendData()" class="form-control btn btn-success" type="submit" name="submit" ng-model="submit" send-mail>Submit</button>

ng-click directive added.

app.directive('sendMail', function($http) {
    return {
      restrict: 'A',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        //alert();
      },
      controller: function($scope) {
        $scope.sendData = function() {
          alert('send data here');
        }
      }
    };
});

here is a DEMO

Sign up to request clarification or add additional context in comments.

8 Comments

But actually I have ng-click already for other function like this: <button class="form-control btn btn-success" type="submit" ng-click="submit($event)">Submit</button>
then call that directive function after the submit($event) function as <button class="form-control btn btn-success" type="submit" ng-click="submit($event); sendData()">Submit</button>, or the proper way to do this is do the ajax in submit() function.
@K.Toress do you really feel that making directive for ajax post.? then why not ng-submit?
absolutely not NO may be he is has some other concerns for it.
@K.Toress I don't think so as hes code looks very straight forward.
|
1

I prefer you shouldn't go for directive if it only contains an ajax call. You can do it just by using ng-click/ng-submit(which is actually meant for forms.) no need of directive here.

You need to correct below certain thing into your code.

  1. We don't need to use ng-model for submit button it doesn't make sense as don't contains any value.
  2. Also you don't need to add action and method attribute on your form, cause anyway you are making from JavaScript code.
  3. While submitting form angular does already provide a directive which is ng-submit.use that would make more sense.
  4. You need to pass data in your post $http.post call.

Markup

<form name="myForm" ng-submit="submit(myForm)" novalidate>
    <div class="form-group has-feedback">
        <label class="control-label">First name:</label>
        <input type="text" class="form-control input-sm " name="uname" ng-pattern="/^[a-zA-Z]{3,20}/" ng-model="user.uname" placeholder="First Name" required/>
        <span style="color:red" ng-show="myForm.uname.$error.pattern">First name cannot be less than 3 letters with no digits</span>
        <span style="color:red" class="error" ng-if="myForm.$submitted && myForm.uname.$error.required">Please fill field above<br></span>
        <span style="color:red" class="hide-while-in-focus" ng-show="myForm.uname.$error.unique">Username already exist<br/></span>
        <span ng-if="myForm.uname.$valid" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
    </div>
    <button class="form-control btn btn-success" type="submit" name="submit" send-mail="">Submit</button>
</form>

Controller

$scope.submit = function(form){
   if(form.$valid){
       $http.post('MailSenderServlet.do', {user: $scope.user})
       .success(function (data) {
           //
       });
   }
   else
     alert("Please validate your form")
}

6 Comments

Why you are passing ` {user: $scope}` as params in post I didn't understand?
@kittu that my bad..it should be $scope.user sending user data from scope to server
This is actual code with some other directives and controllers. So Shall I use the above approach you posted. Please have a look the plunker once plnkr.co/edit/O7EYWTwXUUC7tfvJuXf8?p=preview
I tried pankaj. As the app code is getting bigger its becoming more confusing. Anyway I tried but still didn't work :( Everyday I am learning angular almost whole day to figure only small portion of chapters.
@kittu Ohh..thats cool..but I;d suggested you to follow this step only..which can make your code readable and maintainable..
|
0

The issue with your code is simply the controller part you've written

<body ng-controller="MainCtrl">

Either add a controller part, or just remove it, code works fine.

See Demo : http://jsbin.com/hulujarugu/edit?html,console,output

JS:

 var app = angular.module('myApp', []);
 app.directive('sendMail', function($http) {
     return {
         restrict: 'A',
         require: 'ngModel',
         link: function(scope, element, attrs, ngModel) {
             alert(1);

             $http.post('MailSenderServlet.do').success(function(data) {});
         }
     };
 });

HTML:

    <div class="container">
        <h2 class="text-muted">Registration form</h2><br/>
        <div>
            <form name="myForm" action="RegistrationServlet.do" method="POST" novalidate>
                <div class="form-group has-feedback">
                    <label class="control-label">First name:</label> <input type="text" class="form-control input-sm " name="uname" ng-pattern="/^[a-zA-Z]{3,20}/" ng-model="user.uname" placeholder="First Name" required/>
                    <span style="color:red" ng-show="myForm.uname.$error.pattern">First name cannot be less than 3 letters with no digits</span>
                    <span style="color:red" class="error" ng-if="myForm.$submitted && myForm.uname.$error.required">Please fill field above<br></span>
                    <span style="color:red" class="hide-while-in-focus" ng-show="myForm.uname.$error.unique">Username already exist<br/></span>
                    <span ng-if="myForm.uname.$valid" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>
                </div>
                <button class="form-control btn btn-success" type="submit" name="submit" ng-model="submit" send-mail >Submit</button>
            </form>
        </div>      

1 Comment

in MainCtrl I have this app.controller('MainCtrl', function ($scope) { $scope.user = {}; $scope.submit = function ($event) { if ($scope.myForm.$invalid) { // Or some other update $scope.myForm.$submitted = true; $event.preventDefault(); } }; });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.