如何清理textarea ng-model

时间:2016-12-25 14:26:31

标签: angularjs

我有

 <div class="navbar-collapse">
   <div class="row">
     <div class="col-lg-2 img-fake"></div>
        <div class="col-lg-10 native-item ">
            <textarea class="form-control" rows="5" id="comment" ng-model="newComment" ng-keyup="$event.keyCode == 13 && comment(existingItem,newComment)"></textarea>
          </div>
      </div>
</div>

并且在comment函数中我已经

 $scope.comment = function(existingItem,newComment){
      existingItem.comments.push(newComment);
      $scope.newComment = '';
    } // just adding text from textarea to the list 

所以我想知道为什么textarea的值不会变为空值

2 个答案:

答案 0 :(得分:0)

http://plnkr.co/edit/kmBA3Cco8QNDL8i4eOjz它的工作原理。

    

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.5.x" src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <div class="navbar-collapse">
   <div class="row">
     <div class="col-lg-2 img-fake"></div>
        <div class="col-lg-10 native-item ">
          {{newComment}}
            <textarea class="form-control" rows="5" id="comment" ng-model="newComment" ng-keyup="$event.keyCode == 13 && comment(existingItem, newComment)"></textarea>
          </div>
      </div>
</div>
  </body>

</html>

在你的情况下它不起作用,因为你可能没有定义comment的{​​{1}}属性

existingItem

答案 1 :(得分:0)

我有同样的问题并且像这样修复了

$scope.comment = function(existingItem,newComment){
    existingItem.comments.push(newComment);
    $scope.newComment = 'xx'; // add a random data
    $scope.$evalAsync(function() { $scope.newComment  = '' ; }); //or  use $timeout(function() { $scope.newComment  = '' ; });
}