【问题标题】:Angular JS - Text box not getting updated after clearingAngular JS - 清除后文本框未更新
【发布时间】:2016-06-08 10:40:28
【问题描述】:

我是 Angular JS 的初学者。在创建示例应用程序时,我遇到了以下问题,即使用 JavaScript 清除文本框中的值后无法设置文本框。下面是我的代码:-

<!DOCTYPE html>
 <html>
  <head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <script>
     var app = angular.module("myApp", []);

     app.controller("myCtrl", function () {

        this.showName = function () {
            this.user = { name: "John" };
        }

        this.clear = function () {

            document.getElementById("name").value = "";

        }
    });
</script>
</head>
<body ng-app="myApp">
 <div ng-controller="myCtrl as ctrl" class="container">

    <input type="button" ng-click="ctrl.showName()" value="Show Name"/>
    <input type="text" id="name" ng-model="ctrl.user.name" />
    <input type="button" value="Clear" ng-click="ctrl.clear()" />

 </div>
</body>

她第一次单击“显示名称”按钮时,我在文本框中获取了名称。但是,如果我通过单击“清除”按钮清除文本框,然后再次单击“显示”按钮,则名称不会被填充在文本框中。 谁能告诉我为什么会发生这种情况以及无论如何要解决这个问题?

这是我在 plunkr 中的代码 - http://plnkr.co/edit/MXlH2o?p=preview

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope angularjs-ng-repeat


    【解决方案1】:

    在您的清除函数中执行以下代码以清除值。

    this.user = { name: "" };
    

    【讨论】:

    • 谢谢莫希特。这可行,但你能告诉我的代码不工作的原因吗?
    • 是的,实际上在 Angular 中,当您通过获取该元素清除任何字段时,在这种情况下 ng-model 被阻止,然后双向绑定不起作用,这就是它不起作用的原因。
    【解决方案2】:

    这样清除名字,

    this.clear = function () {
                    this.user.name = "";
                }
    

    【讨论】:

      【解决方案3】:

      您不需要控制器中的 clear() 方法,只需利用 angular 中的双重绑定,单击按钮时将用户名设置为空字符串,视图将随之更新。

      <input type="button" value="Clear" ng-click="ctrl.user.name = ''" />
      

      【讨论】:

      • 谢谢卡里姆。但是你能告诉我上面的代码不起作用的原因吗?
      • 好吧,我只是不认为这是使用角度的正确方法。使用 Angular,您不应该以这种方式操作 dom 以避免弄乱本机 javascript,而是使用提供的工具。欢呼
      【解决方案4】:

      将清除函数更改为此代码

      this.clear = function () {
           this.user.name="";
      }
      

      【讨论】:

      • @Bamnaam,你能告诉 OP 他需要这样做的原因吗? Stackoverflow 中的答案是非常清晰和描述性的。所以请记住这一点。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多