javascript 在 AngularJS 中重置 textarea 后 Ng 模型不更新
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28353426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ng-model not updating after resetting textarea in AngularJS
提问by Michelangelo
I have been scratching my head over this problem for a while now. I have made a textarea and created a model with ng-model. This works all fine. I also have a button that uses plain Javascript for resetting the textarea. The binding stops working at that moment I click this button and I still can see my text in the other field, but the textarea is emtpy. I have recreated the problem here Fiddle.
我一直在为这个问题挠头一段时间。我制作了一个 textarea 并使用 ng-model 创建了一个模型。这一切正常。我还有一个按钮,它使用纯 Javascript 来重置文本区域。绑定在我单击此按钮的那一刻停止工作,我仍然可以在另一个字段中看到我的文本,但 textarea 是空的。我在这里重新创建了这个问题Fiddle。
window.onload = function () {
document.getElementById('btn').onclick = function () {
document.getElementById('textarea').value = "";
};
};
Am I missing something here or is this not how binding works in Angular. When I start retyping it starts 'listening' again and displays the correct text.
我在这里遗漏了什么,或者这不是绑定在 Angular 中的工作方式。当我开始重新输入时,它会再次开始“聆听”并显示正确的文本。
Does somebody have a clue or encountered this problem before?
有人有线索或以前遇到过这个问题吗?
Thanks in advance.
提前致谢。
回答by Scottie
Here's a fiddle that will do what you are asking, but it's very un-angular.
这是一个可以满足您要求的小提琴,但它非常没有棱角。
http://jsfiddle.net/tk0a5nf1/3/
http://jsfiddle.net/tk0a5nf1/3/
window.onload = function () {
document.getElementById('btn').onclick = function () {
var scope = angular.element(document.getElementById('textarea')).scope();
scope.txt = "";
scope.$apply();
};
};
Here is a more angular way of doing this:
这是一种更有角度的方法:
<div ng-app>
<textarea id="textarea" ng-model="txt"></textarea>
<div>{{txt}}</div>
<button id='btn' ng-click='txt=""'>Reset textarea</button>
</div>
回答by AWolf
Not sure why you don't use angular to reset your text area.
不知道为什么不使用 angular 来重置文本区域。
You can do a reset with ng-click="txt=''"
with-out a function in your controller but it's better to do it like this ng-click="reset()"
.
您可以ng-click="txt=''"
在控制器中没有功能的情况下进行重置,但最好这样做ng-click="reset()"
。
For a demo see below and here at jsFiddle.
有关演示,请参见下面和这里的jsFiddle。
var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', function ($scope) {
$scope.txt='';
$scope.reset = function() {
$scope.txt = '';
};
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.10/angular.js"></script>
<div ng-app="myApp">
<div ng-controller="MainCtrl">
<textarea id="textarea" ng-model="txt">
</textarea>
<div>{{txt}}</div>
<!--<button id='btn' ng-click="txt=''">Reset textarea</button>-->
<button id='btn' ng-click="reset()">Reset textarea</button>
</div>
</div>