Ger*_*rdo 3 jquery angularjs cordova
我在角度服务中有一个ajax函数,它根据后端服务检查用户的凭据.我已经简化了这个电话了.当我使用$ http服务发出AJAX请求时,promise API可以正常工作:
function isOnline(){
    return $http.get(constants.dataUrl)
           .success(function(){return})
           .error(function(){return;});
}
function checkCredentials(){
    var online = isOnline();
    var checkCreds = online.then(function(){
        alert("Get succeeded");
    },
    function(response){
        alert("Get did not succeed");
    });
    return checkCreds;
}  
我看到当时定义的函数调用了.当我使用jQuery ajax方法时,解析和延迟方法似乎没有传播并在online.then中触发正确的方法.以下代码不起作用:
function isOnline(){
    var defer = $q.defer();
    $.ajax({
      url: constants.dataUrl,
      dataType: 'json',
      beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', basicAuthenticationToken());
      },
      error: function (xhr, ajaxOptions, thrownError) {
        alert("I am not online");
        defer.reject("I am not online");
      },
      success: function (data) {
        alert("I am online");
        defer.resolve(data);
      }
    });
    return defer.promise;
}
function checkCredentials(){
    var online = isOnline();
    var checkCreds = online.then(function(){
        alert("Get succeeded");
    },
    function(response){
        alert("Get did not succeed");
    });
    return checkCreds;
} 
我可以不使用promise API和普通的jQuery ajax方法吗?我想替换这些调用的原因与一个复杂的PhoneGap场景有关,它似乎不适用于Angular $ http.
Angularjs需要被告知其外部发生的变化.由于ajax事件由jquery处理,因此您需要进行应用.取决于函数的位置(可能是$ scope或$ rootScope)
defer.reject("I am not online");
$scope.$apply();
....
defer.resolve(data);
$scope.$apply();
这将让角知道重新处理自己.以下是关于它的文档:http://docs.angularjs.org/api/ng.$rootScope.Scope#$apply
您可以在任何时候使用此功能,只需要在角度以外编写javascript,但需要将其连接到它.
| 归档时间: | 
 | 
| 查看次数: | 2037 次 | 
| 最近记录: |