Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何将AngularJS与Rails表单一起使用?_Ruby On Rails_Angularjs_Ruby On Rails 4_Simple Form - Fatal编程技术网

Ruby on rails 如何将AngularJS与Rails表单一起使用?

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函数的控制器,该函数接受

我在AngularJS中使用simple_表单:

= 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];
    });
  };
});
希望有帮助