2013-08-30 88 views
2

我在rails應用上使用了angularjs。我想製作一個分頁服務器端數據的搜索表單。

這裏是我的形式:

<input type="text" class="search-query" placeholder="Search Products" ng-model="search_terms" />

我的軌控制器可以接受JSON或HTML請求:

def index 
    # .... 
    respond_to do |format| 
    format.json { 
     # ... 
    } 
    format.html { 
     # ... 
    } 
    end 
end 

這裏是我的角度控制器。出於某種原因,$ http服務只能返回rails默認的html響應,而不是json響應。

$scope.$watch('search_terms',function(newValue,oldValue){ 
    var query = newValue; 

    $http.get('/products',{params:{search_terms:query}, responseType:'json'}).success(function(data) { 
    // do something 
    }); 

}); 

如果我用這個jQuery.get I DO找回所需的JSON響應,那麼爲什麼角給我的html?

jQuery.get('/products',{search_terms:query},function(data){ 
    console.log(data); 
    }, 'json') 

我檢查網絡報頭和角呼叫和呼叫的jQuery之間的主要區別是,角不設置X-請求-隨着頭爲「的XMLHttpRequest」?

如果我添加,那麼我可以得到它的工作。

$http.get('/products',{params:{search_terms:query}, responseType:'json', 'headers':{'X-Requested-With':'XMLHttpRequest'}}).success(function(data) { 
    // do something 
    }); 

但是對Angular來說,新手並不知道這是否是解決此問題的正確方法。感覺有點笨重,每次都必須這樣做。有沒有更好的方法,或者這是你如何使用Angular和Rails?

+0

可能重複失敗的升級從1.1.0到1.1.1後](http://stackoverflow.com/questions/15811062/angular-js-fails-after-upgrade-from-1-1-0-to-1-1-1) – zsong

+0

https://github.com/angular /angular.js/issues/1004 – zsong

回答

4

我遇到了同樣的事情,並因此而感到沮喪。我的第一個解決方案是一個有點警察出來的,我結束了這種寶石會:

https://github.com/FineLinePrototyping/angularjs-rails-resource

但有一個多一點的經驗之後,我發現它與角度沒有設置正確的頭做。

angular.module('yourmodule').run(['$http', function($http) { 
    $http.defaults.headers.common['Accept'] = 'application/json'; 
    $http.defaults.headers.common['Content-Type'] = 'application/json'; 
}]); 

參考:http://angulartutorial.blogspot.com/2014/05/set-headers-for-all-http-calls-in.html

記住的情況也存在於request.xhr

https://github.com/rails/rails/issues/16444

[角JS的