2016-07-07 57 views
-3

由於某些原因,我更願意使用JQuery直接dom操作編寫我的應用程序。不過,我認爲角度$ http服務比$ ajax方法好得多。我怎樣才能從一個非角度的Web應用程序調用$ http?使用jquery的角度服務

我想我可以創建一個虛擬應用程序/控制器,其唯一目的是將引用複製到$ http到全局範圍。

<div ng-app="xx" ng-controller="yy"/> 
<script> 
    var myhttp = null; 
    angular.module('xx',[]).controller('yy', function($http) { myhttp = $http; }); 
</script> 

有沒有更簡單的方法?

+2

嗨,約翰,你目前正在爲$ http加載整個角度。我建議你要麼選擇完全使用angular或jquery。混合兩者並不是那麼好,http服務是爲角度而構建的,並且不會在其他地方使用,它喜歡$ digest循環和許多其他部分。 –

回答

1

爲實現Angular的$ http接口的jQuery的$ .ajax創建一個適配器。

您目前的做法並不理想。如您所知,$http與Angular的DI實施緊密結合。

我很好奇什麼是AngularJS $http服務,你更喜歡jQuery的Ajax方法嗎?雙方都承諾承諾。

+0

在$ http中承諾具有一致的參數(響應),而在$ ajax中它們令人困惑,有時候是jqxhr。有時是第一,有時是第三。有時是activex。此外,我測試了依賴於$ http的代碼。我不想重寫它使用$ ajax。但我喜歡你的建議。我會去做。 –

0

以下Martin的建議是我寫的代碼。它沒有完全測試,

// This is a wrapper to cause the $.ajax api to act like the $http api (mostly) 
function fake$http() { 
    'use strict'; 
    var $http = function (settings) { 
     return $.ajax(settings) 
     .then(function (data, status, jqxhr) { 
      return { 
       data: data, 
       status: jqxhr.status, 
       config: settings, 
       statusText: jqxhr.statusText 
      }; 
     }, function (jqxhr) { 
      return { 
       data: jqxhr.responseText, 
       status: jqxhr.status, 
       config: settings, 
       statusText: jqxhr.statusText 
      }; 
     }); 
    }; 

    $http.get = function (url, config) { 
     return $http($.extend({ url: url, method: 'GET' }, config)); 
    }; 
    $http.post = function (url, data, config) { 
     return $http($.extend({ url: url, method: 'POST', data: data }, config)); 
    }; 
    $http.put = function (url, data, config) { 
     return $http($.extend({ url: url, method: 'PUT', data: data }, config)); 
    }; 
    $http.delete = function (url, config) { 
     return $http($.extend({ url: url, method: 'DELETE' }, config)); 
    }; 
    return $http; 
} 

response.header丟失。許多其他差異,如cors,jsonp等,等等。