Ruby on rails 如何将AngularJS与Rails表单一起使用?
我在AngularJS中使用simple_表单:Ruby on rails 如何将AngularJS与Rails表单一起使用?,ruby-on-rails,angularjs,ruby-on-rails-4,simple-form,Ruby On Rails,Angularjs,Ruby On Rails 4,Simple Form,我在AngularJS中使用simple_表单: = simple_form @post do |f| = f.input :title, input_html: { "ng-model" => "title" } 它对于我在新帖子上的场景非常有效,但对于在现有帖子上编辑,它不会绑定/填充表单上帖子标题的现有值。据我所知,Rails已经填充了该值,但AngularJS在页面加载后将其清除,因为$scope.title为空。我发现诀窍在于实际创建一个带有init函数的控制器,该函数接受
= simple_form @post do |f|
= f.input :title, input_html: { "ng-model" => "title" }
它对于我在新帖子上的场景非常有效,但对于在现有帖子上编辑,它不会绑定/填充表单上帖子标题的现有值。据我所知,Rails已经填充了该值,但AngularJS在页面加载后将其清除,因为
$scope.title
为空。我发现诀窍在于实际创建一个带有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;
}
});
<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>
AngularRails.controller('PostFormCtrl', function($scope) {
$scope.init = function(input) {
Object.keys(input).forEach(function(key) {
$scope[key] = input[key];
});
};
});
您必须将视图转换为haml,但它应该如下所示:
//= require_self
AngularRails = angular.module('AngularRails', []);
AngularRails.controller('PostFormCtrl', function($scope) {
$scope.init = function(title) {
$scope.title = title;
}
});
<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>
AngularRails.controller('PostFormCtrl', function($scope) {
$scope.init = function(input) {
Object.keys(input).forEach(function(key) {
$scope[key] = input[key];
});
};
});
希望有帮助