如何从 Angular 获取/复制/访问 Rails 中的数组

How can i get/copy/access the array that is in Rails from Angular

本文关键字:Rails 数组 访问 复制 Angular 获取      更新时间:2023-09-26

如何从 Angular 获取/复制/访问 Rails 中的数组?我的def new函数中有一个字符串数组,称为@array_of_names,并希望在我的Angular函数中具有相同的数组(@array_of_names)。有什么方法可以做到这一点,这样我就可以在我的 Angular 方面@array_of_names?

轨道文件

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!";
  }
})()

您可以通过 AJAX 完成此操作。您需要在 Rails 应用程序中设置一条路由,该路由返回一个 JSON 对象供 Angular 使用。

导轨
controller_name替换为控制器名称

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

def get_names
  render json: read_names()
end

Routes (/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'];

请参阅此链接以真正了解 angular 在做什么:https://docs.angularjs.org/api/ng/service/$http

这里有一个链接,解释了如何使用Rails和更复杂的JSON响应。https://www.leighhalliday.com/responding-with-json-in-rails