2016-07-13 23 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