lostcoder12345 lostcoder12345 - 4 months ago 56
AngularJS Question

Bind ng-model dynamically with data from ng-repeat (Angular 1.5.7)

****EDIT: PROBLEM SOLVED! Neuronet's solution was the answer:

<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>


Below is my original post:

I've spent the past 3 hours on this problem. I have an array of posts that I have passed from my controller to my template under the name "posts". Each post in posts is an array holding various key-value pairs such as "id" (value being an integer), "content" (value being a string), etc. I want to include a form to send a PostComment post to my api. The PostComment post requires that I send it a foreign key (representing the related post) and a content field. I wish to get the foreign key dynamically from ng-repeat .

My template looks like this:

<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>


The pertinent part of my controller looks like this:

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


I am attempting to get the foreign key from post.id (the "post" is from post in $ctrl.posts in ng-repeat). I cannot seem to figure out a way to do this. I have tried both value="{{ post.id }}" and ng-value="{{ post.id }}" but for various reasons neither works. Ng-value only works on radio, but I cannot automatically check the option, and value does not work together with ng-model since they are both competing to set the value.

I'd be much obliged to anyone who could help me.

Answer

Why are you using the CommentArray ? just use comment as your model You can pass a post id in postCommentSubmit

<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>
Comments