在ng-repeat中输入ng-model

时间:2016-07-21 21:24:31

标签: angularjs

我正在重复一个任务列表,我希望其他用户能够使用输入字段进行评论。我用ng-repeat重复列表,并尝试将注释输入的值发送到具有ng-model和scope的服务器。我正在通过控制台日志记录进行测试,但它显示为未定义。请帮忙!

HTML:

<div class="taskContainer">
  <div ng-repeat='task in taskList' class="task">
    <div class="postedBy">
      <h6>{{task.user.userName}}</h6>
    </div>
    <h4>{{task.taskText}}</h4>
    <div class="comments">
        <input ng-model="newComment" type="text" placeholder="comments">
        <button ng-click='comment(task.taskId)' type="button" name="button">Add</button>
      <h6>{{task.commentText}}</h6>
    </div>
  </div>
</div>

JS控制器:

$scope.comment = function(id,text){
      console.log(`send comment text ${$scope.newComment}`);
      console.log(`task Id: ${id}`);
    };

这是我第一次尝试使用ng-repeat显示主题

3 个答案:

答案 0 :(得分:1)

您获得undefined因为ngRepeat创建了自己的$scope

始终使用ngModelDot Rule分配controller-as-syntax

把它放在你的控制器中:

$scope.model = {};

然后使用ngModel

<input ng-model="model.newComment[$index]" type="text" placeholder="comments">

然后你可以这样:

<div class="taskContainer">
  <div ng-repeat="task in taskList track by $index" class="task">
    <div class="postedBy">
      <h6>{{task.user.userName}}</h6>
    </div>
    <h4>{{task.taskText}}</h4>
    <div class="comments">
        <input ng-model="model.newComment[$index]" type="text" placeholder="comments">
        <button ng-click='comment($index)' type="button" name="button">Add</button>
      <h6>{{task.commentText}}</h6>
    </div>
  </div>
</div>

$scope.comment = function(index) {
  console.log(`send comment text ${$scope.model.newComment[index]}`);
  console.log(`task Id: ${taskList[index].id}`);
};

注意:您的函数需要2个参数,您应将其更改为:

$scope.comment = function(id) {

答案 1 :(得分:0)

感谢@ developer033的帮助。 这就解决了我的问题:

HTML:

<div class="taskContainer">
  <div ng-repeat="task in taskList track by $index" class="task">
    <div class="postedBy">
      <h6>{{task.user.userName}}</h6>
    </div>
    <h4>{{task.taskText}}</h4>
    <div class="comments">
        <input ng-model="model.newComment[$index]" type="text" placeholder="comments">
        <button ng-click='comment(task.taskId,$index)' type="button" name="button">Add</button>
      <h6>{{task.commentText}}</h6>
    </div>
  </div>
</div>

和JS:

$scope.model = {};
    $scope.comment = function(id, index) {
      console.log(`send comment text ${$scope.model.newComment[index]}`);
      console.log(`task Id: ${id}`);
    };

答案 2 :(得分:-1)

HTML,

<input ng-model="newComment" type="text" placeholder="comments">
<button ng-click='comment(task.taskId, newComment)' type="button" name="button">Add</button>

的JavaScript,

$scope.comment = function(id, text) { 
  console.log(`task Id: ${id}`);
  console.log(`send comment text ${text}`);
};