ng-repeat 中的表单

Form in ng-repeat

观看次数:

<ul ng-repeat="x in posts.post">
    {{x.name}}  {{x._id}} {{x.post}} {{x.user_id}} 
    <br>
    <form>
        <textarea  ng-model='new_comment.comment' name="comment" rows="4" cols="50">
        </textarea> 
        <br>
        <input type="submit" value="Post Comment!" ng-click="addComment(x._id)" >
    </form>
</ul>

这是控制器:

$scope.addComment = function(id) {
    postFactory.addComment(id, $scope.new_comment, function () {
        postFactory.getComment(function (data) {
            $scope.comments = data;
        });
        $scope.new_comment = {};
    });
};

这是工厂:

factory.addComment = function(id, info, callback) {
    console.log(info);
    $http.post("/saveComment/" + id , info).success(function() {
        comments.push({name: info.name, age: info.description, category: info.category});
        callback(comments);
    });
};

我这里有这些代码。当表单包裹在 ng-repeat 标签内时,它不会在我的 controller/factory 中输出任何内容,但是当我删除它时,它会输出我想要的内容。但我需要访问循环的 ID (x._id)。

而不是使用 <form> 标签

尝试<div ng-form="your_form_name">

你应该这样试试

<ul ng-repeat="x in posts.post">
    {{x.name}}  {{x._id}} {{x.post}} {{x.user_id}} 
    <br>
    <textarea ng-form="form" ng-model='new_comment.comment' name="comment" rows="4" cols="50">
    </textarea>
    <br>
    <input type="button" value="Post Comment!" ng-click="addComment(x._id)" >
</ul>

您不得声明 $scope.new_comment。 试试这个:

$scope.new_comment = {}; //right after your controller starts.

控制器无法访问 new_comment.comment,因为 ng-repeat 创建了它自己的范围。如果您在控制器中定义它,您所有的评论输入字段都将绑定到同一模型。

最简单的解决方案是使用函数传递注释值。

addComment (x.id, new_comment.comment)

请使用 li 来包装你的所有 html 并在 li 而不是 ul 上应用 ng-repeat。