Ruby on rails 将数据从Rails发送到AngularJS

Ruby on rails 将数据从Rails发送到AngularJS,ruby-on-rails,angularjs,Ruby On Rails,Angularjs,假设您有一个带有控制器操作的Rails应用程序#index,我如何才能在视图中将@items赋予Angular,而不必在索引视图中拥有大量javascript逻辑 def index @items = Item.all end 这种观点是: <ul> <li ng-repeat="item in items">{{item.name}}</li> </ul> {{item.name} 关键问题:通过Rails传递到视图的Angul

假设您有一个带有控制器操作的Rails应用程序
#index
,我如何才能在视图中将
@items
赋予Angular,而不必在索引视图中拥有大量javascript逻辑

def index
  @items = Item.all
end
这种观点是:

<ul>
  <li ng-repeat="item in items">{{item.name}}</li>
</ul>
  • {{item.name}

关键问题:通过Rails传递到视图的Angular列出数据的好做法是什么?

索引操作中,您希望使用json或javascript进行响应:

def index
  @items = Item.all

  respond_to do |format|
    format.json { render json: @items }
    format.js
  end
end
在角度方面,您可以使用$http服务向项目url发出XHRJSONP请求。文档中的更多信息:

文档中的示例:

$http({method: 'GET', url: '/items'}).
    success(function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
    }).
    error(function(data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });

在这个主题上还有一个很好的railscast:

我不想把这个应用程序转换成API。我也不想把这一切都安排好。对于一个简单的
ng repeat
,这看起来非常有用。据我所知,没有别的办法了。如果您想进行标准的JS或JQueryAjax调用,您也必须这样做……但我不想进行Ajax调用。我只想从Rails传递角度数据。就像我没有用Rails制作Angular应用程序一样,我有一个带有Angular的Rails应用程序。你在哪里实例化Angular模块、控制器和项目范围?也许你想看看我在回答最后提到的铁路公司。