Liglo App
Liglo App

Reputation: 3819

angularjs - $http request not working within a directive definition

This is how my code is structured:

View:

<form action="./?app,signin" method="post" id="signinform" name="signinform" novalidate vibrating loginform>
(...)
</form>

JavaScript:

angular.module('loginApp', [])
    .directive('loginform', function ($http) {
         return function (scope, elm, attrs, ctrl) {
            elm.submit(function (e) {               
                if ($(elm).hasClass('ng-valid')) {
                   console.log('X'); 
                   $http.get('./?app,validateCredentials&username=admin&password=admin')
                        .success(function (d, s, h, c) {
                            console.log('A');

                        })
                        .error(function(d, s, h, c) {
                            console.log('B');
                        })
                    ;
                    e.preventDefault();         
                }
            });
         }
    })    
.controller('loginCtrl', function($scope, $filter, $window, $location, $http) { (...)

The 'X' is logged in the console, but the $http request does not work. Any idea why?

Upvotes: 1

Views: 1729

Answers (1)

robertklep
robertklep

Reputation: 203231

Since you're calling Angular code from within a non-Angular event handler, try wrapping the request in scope.$apply():

elm.submit(function (e) { 
  if ($(elm).hasClass('ng-valid')) { 
    console.log('X');
    scope.$apply(function() {
      $http.get('./?app,validateCredentials&username=admin&password=admin')
        .success(function (d, s, h, c) {
          console.log('A');

        })  
        .error(function(d, s, h, c) {
          console.log('B');
        })  
      ;
    });
    e.preventDefault();
  } 
});

Upvotes: 4

Related Questions