1

这就是我的代码的结构:

看法:

<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) { (...)

'X' 记录在控制台中,但 $http 请求不起作用。知道为什么吗?

4

1 回答 1

4

由于您是从非 Angular 事件处理程序中调用 Angular 代码,请尝试将请求包装在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();
  } 
});
于 2013-06-28T05:56:41.240 回答