【问题标题】:Textarea won't clear after clearing attached model in angularjs清除angularjs中的附加模型后Textarea不会清除
【发布时间】:2016-07-02 19:53:24
【问题描述】:

我有一个textarea 附加到一个名为newNoteText$scope 变量。 html是:

<textarea spellcheck="true"               
          ng-model="newNoteText"></textarea>

还有一个按钮可以保存输入的笔记。

<button type="button" class="btn btn-default" 
       ng-click="btnPost_clicked(newNoteText)">Post
</button>

这里是控制器函数btnPost_clicked

        $scope.btnPost_clicked = function(newNoteText) {
            $scope.addNote(newNoteText);
            $scope.newNoteText = '';
        }

我通过 console.log 确认 $scope.newNoteText 被重置为空字符串。但 textarea 仍然保存旧文本。

【问题讨论】:

  • 我不认为这应该是问题...text-areang-repeat 里面吗?
  • @PankajParkar 不,它不在 ng-repeat 中。
  • @Legion 如果您发布更多代码可能会有所帮助
  • @Legion 你能在 plunkr 中重现问题吗?
  • 你能在一些演示小提琴或 plunkr 中重现它吗?对我来说它有效:jsfiddle.net/5darc76z 看起来像是一些错字

标签: javascript angularjs


【解决方案1】:

只有在 $scope.addNote(newNoteText) 中出现错误时才会发生这种情况。请参阅下面的代码并尝试我创建的 jsfiddle。我只是在 addNote 中记录 newNoteText,一切似乎都正常。

HTML:

<div ng-controller="MainCtrl">

  <textarea spellcheck="true"               
          ng-model="newNoteText"></textarea>

  <div>{{txt}}</div>

  <button type="button" class="btn btn-default" 
       ng-click="btnPost_clicked(newNoteText)">Post
</button>
</div>

JavaScript:

var app = angular.module('myApp', []);

app.controller('MainCtrl', ['$scope', function($scope) {
  $scope.txt = '';

  $scope.btnPost_clicked = function(newNoteText) {
    $scope.addNote(newNoteText);
    $scope.newNoteText = '';
  };

  $scope.addNote = function(newNoteText) {
    console.log(newNoteText);
  }
}]);

jsfiddle:https://jsfiddle.net/nikdtu/d89ftrmg/

【讨论】:

  • 这不是发生这种情况的唯一原因...ng-ifng-include 中的子范围嵌套也会破坏原语的绑定
  • 是的,但你不认为在那种情况下,即使我们不应该能够调用 $scope.btnPost_clicked 吗?
  • 不...因为函数不是原语所以在子作用域中有继承
猜你喜欢
  • 2014-12-12
  • 1970-01-01
  • 2020-04-24
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-14
相关资源
最近更新 更多