2016-07-13 25 views
0

我如何獲取/複製/訪問從Angular的Rails數組?我在我的def new函數中有一個名爲@array_of_names的字符串數組,並且想要在我的Angular函數中使用相同的數組(@array_of_names)。有什麼辦法做到這一點,所以我可以在我的Angular方面有@array_of_names?我如何獲取/複製/訪問從角度的Rails數組

Rails的文件

def new 
    @account = Account.new 
    @array_of_names = read_names() 
end 

角文件

(() => { 

    angular 
    .module('accounts') 
    .controller('AccountsController', AccountsController) 

    AccountsController.$inject = [] 

    //testing function 
    function AccountsController() { 
    let vm = this; 
    vm.claim = "Hello, world!"; 
    } 

})() 
+0

使用'工作的鏈接$ http'做出ajax請求,並有軌道發送json響應 – charlietfl

+0

@charlietfl,我只是最近纔開始使用rails,這是我第一天的Angular經驗....你能澄清一下你意思? – user6465508

+0

https://docs.angularjs.org/api/ng/service/$http – charlietfl

回答

0

您可以通過AJAX實現這一目標。您需要在Rails應用程序中設置一個路徑,該路徑返回一個供Angular使用的JSON對象。

Rails的
更換CONTROLLER_NAME與控制器名稱

控制器(/app/controllers/controller_name.rb):

def get_names 
    render json: read_names() 
end 

路線(/config/routes.rb ):

get '/get_names' => 'controller_name#get_names' 

function AccountsController($http){ 

    var vm = this; 

    $http.get('/get_names').then(function(response){ 
    vm.names = response.data; 
    }); 
} 

AccountsController.$inject = ['$http']; 

請參閱此鏈接真正理解的角度是這樣做的:https://docs.angularjs.org/api/ng/service/$http

這裏是解釋如何使用Rails和更復雜的JSON響應 https://www.leighhalliday.com/responding-with-json-in-rails