【问题标题】:How to use AngularJS with Rails Form?如何将 AngularJS 与 Rails 表单一起使用?
【发布时间】:2014-08-30 20:55:06
【问题描述】:

我将 simple_form 与 A​​ngularJS 一起使用:

= simple_form @post do |f|
  = f.input :title, input_html: { "ng-model" => "title" }

它非常适合我在新帖子上的场景,但对于现有帖子的编辑,它不会绑定/填充表单上帖子标题的现有值。我认为 Rails 已经填写了该值,但 AngularJS 在页面加载后将其删除,因为 $scope.title 为空白。

【问题讨论】:

    标签: ruby-on-rails angularjs ruby-on-rails-4 simple-form


    【解决方案1】:

    我发现诀窍是实际创建一个具有 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];
        });
      };
    });
    

    希望有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      • 2015-12-30
      • 2014-08-10
      • 1970-01-01
      相关资源
      最近更新 更多