kittu
kittu

Reputation: 7008

custom directive is not getting called in angular js

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>

Upvotes: 1

Views: 1323

Answers (3)

Pankaj Parkar
Pankaj Parkar

Reputation: 136144

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")
}

Upvotes: 1

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

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

Upvotes: 1

Roy M J
Roy M J

Reputation: 6938

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>      

Upvotes: 0

Related Questions