angularjs - $ http请求在指令定义中不起作用

时间:2013-06-28 05:49:10

标签: ajax angularjs

这就是我的代码的结构:

查看:

<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请求不起作用。知道为什么吗?

1 个答案:

答案 0 :(得分: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();
  } 
});