【问题标题】:Hidden form field not working in Angular Js隐藏的表单字段在 Angular Js 中不起作用
【发布时间】:2026-02-18 17:20:04
【问题描述】:

这是我在 laravel 应用程序中的 html 表单,它有隐藏字段,这些隐藏值需要发送到 Angular js 控制器。

<form accept-charset="UTF-8" enctype="multipart/form-data">
    <input name="_token" type="hidden"  value="{{ csrf_token() }}">
    <input name="user_id" type="hidden"  value="{{ Auth::user()->id }}">
    <input name="post_id"  type="hidden" value="<% post.id %>" >
    <input name="published_at" type="hidden" value="{{ Carbon\Carbon::today()->format('Y-m-d') }}">
    <input class="form-control" placeholder="comment"  ng-model="contentField" type="text" >
    <button type="submit" ng-click="addComment()">comment</button>
</form>

我的 Angular 控制器如下

 $scope.addComment = function(){
     var comment = {
       user_id: $scope.user_id,
       content: $scope.contentField,
       post_id: $scope.post_id,
       published_at: $scope.published_at
 };

我只是在控制器中获取 contentField 的值,请帮我解决这个问题!

【问题讨论】:

  • 我会放弃使用 type="hidden" 和 value=".." 来支持角度指令 ng-hide="true" 和 ng-model="..."。将值设置为等于某物不会将其绑定到角度模型。此外,将您的评论变量作为 $scope.comment 放在 $scope 上,并直接绑定到它,如 ng-model="comment.user_id"
  • 还有其他方法可以在不使用 ng-model 的情况下发送隐藏的表单值吗?

标签: angularjs laravel angularjs-scope hidden-field


【解决方案1】:

您的隐藏导入中似乎缺少ng-model 标记。因为那个角度不知道如何或在哪里将隐藏的输入值绑定到$scope。将这些标签添加到所有隐藏的输入应该可以解决您在 $scope 上找不到它们的问题。

【讨论】:

  • 我之前尝试过 ng-model。不使用隐藏字段它工作正常但是没有发送使用隐藏字段值,这里实际的问题是我必须使用表单将隐藏值发送到角度函数。
  • 如果您使用 ng-hide 而不是 type="hidden" 您将能够根据需要与模型进行交互。
  • 现在可以工作了,但是当使用回调方法推送值时,只有评论推送到数组。我需要将 userName 和 userImage 推送到数组我如何也可以推送它们。有什么想法吗?
【解决方案2】:

我们可以像这样简单地尝试:

<input type="hidden" ng-model="post_id" ng-init="post_id=<% post.id %>"/>

<input type="hidden" ng-model="post_id" value="{{post_id}}" ng-init="post_id=<% post.id %>"/>

<input type="hidden" ng-model="post_id" value="<% post.id %>" ng-init="post_id=<% post.id %>"/>

注意:这里ng-init 正在执行绑定来自另一个模型或对象或直接值的任何技巧:)

【讨论】: