javascript - 将 ng-model 与 ng-repeat 中的数据动态绑定(bind)(Angular 1.5.7)

标签 javascript angularjs

****编辑:问题解决了! Neuronet 的解决方案就是答案:

<div ng-repeat="post in $ctrl.posts">
<textarea class="postBox"  ng-model="$ctrl.comment.content" name="content" /></textarea>
<input type="submit" id="submit" value="Submit" ng-click="$ctrl.postCommentSubmit(post.id)" />
</div>

以下是我的原帖:

过去我花了 3 个小时来解决这个问题。我有一系列帖子,已从 Controller 传递到模板,名称为“posts”。 posts 中的每个帖子都是一个数组,包含各种键值对,例如“id”(值为整数)、“content”(值为字符串)等。我想包含一个表单来将 PostComment 帖子发送到我的API。 PostComment 帖子要求我向其发送一个外键(代表相关帖子)和一个内容字段。我希望从 ng-repeat 动态获取外键。

我的模板如下所示:

            <div ng-repeat="post in $ctrl.posts">
              ....
              <form ng-submit="$ctrl.postCommentSubmit()">

                <input class="hidden" type="text" ng-model="$ctrl.postCommentArray.postForeignKey" value="{{ post.id }}" name="postid"  /> 
                <textarea class="postBox"  ng-model="$ctrl.postCommentArray.content" name="content" /></textarea>
                <input type="submit" id="submit" value="Submit" />

              </form>

            </div>

我的 Controller 的相关部分如下所示:

self.postCommentArray = {
        content: '',
        postForeignKey:  '',
      };

我正在尝试从 post.id 获取外键(“post”来自 ng-repeat 中 $ctrl.posts 中的帖子)。我似乎想不出办法做到这一点。我尝试了 value="{{ post.id }}"和 ng-value="{{ post.id }}"但由于各种原因都不起作用。 ng-value 仅适用于 radio ,但我无法自动检查该选项,并且 value 不能与 ng-model 一起使用,因为它们都在竞争设置值。

我非常感谢任何可以帮助我的人。

最佳答案

为什么使用 CommentArray ?只需使用评论作为您的模型 您可以在 postCommentSubmit 中传递帖子 id

<div ng-repeat="post in $ctrl.posts">
<textarea class="postBox"  ng-model="post.comment.content" name="content" /></textarea>
<input type="submit" id="submit" value="Submit" ng-click="$ctrl.postCommentSubmit(post.id)" />
</div>

关于javascript - 将 ng-model 与 ng-repeat 中的数据动态绑定(bind)(Angular 1.5.7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38420982/

相关文章:

javascript - 使用 Nodejs 信息填充选择框

javascript - 将背景应用到 ionic 侧菜单

javascript - 如何让这段代码看起来更好

php - 将访问者从我的页面重定向到其他域(eshop)并在购买产品后将其重定向回来?

javascript - HTML5 视频,使用 Javascript 更改源,无法在 Safari 上加载,在 Chrome 上正常

javascript - 如何动态绑定(bind) Angular 图表的数据

javascript - 我如何使用 Angular JS 作为模板引擎?

javascript - 如何使用纯 Javascript 从 Div 内的 Span 获取文本值

javascript - 删除所有带有 javascript 类的元素

javascript - 根据日期将项目添加到两个数组( future 日期和过去日期)中