这就是我的代码的结构:
查看:
<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请求不起作用。知道为什么吗?
答案 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();
}
});