我发现诀窍是实际创建一个具有 init 函数的控制器,该函数采用您想要的值。就我而言,我刚刚创建了一个如下所示的app/assets/javascripts/angular_app.js 文件:
//= require_self
AngularRails = angular.module('AngularRails', []);
AngularRails.controller('PostFormCtrl', function($scope) {
$scope.init = function(title) {
$scope.title = title;
}
});
您必须将视图翻译成haml,但它应该看起来像这样:
<div ng-app="AngularRails">
<div ng-controller="PostFormCtrl" ng-init="init('<%= @post.title %>')">
<%= form_for @post, html: {name: "postForm", "novalidate" => true} do |f| %>
<%= f.text_field :title, "ng-model" => "title", required: true %>
<%= f.submit "ng-disabled" => "postForm.$invalid" %>
<% end %>
</div>
</div>
记得将 angular_app 文件包含到 application.js 中,它应该是世界的。显然,这不是一个非常健壮的解决方案,但您可以使用活动模型序列化程序将 rails 对象转换为 json 对象。然后,将该 json 对象传递给 init 函数并在控制器中,遍历该 json 对象的键/值对并将它们设置为 $scope。像这样的:
AngularRails.controller('PostFormCtrl', function($scope) {
$scope.init = function(input) {
Object.keys(input).forEach(function(key) {
$scope[key] = input[key];
});
};
});
希望有帮助!