0

我是Angular JS的初学者。在创建示例应用程序,我曾经遇到过一个文本框的下面问题没有得到一次设定的值,其清除使用JavaScript.Below是我的代码: -Angular JS - 文本框在清除后没有更新

<!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

回答

2

在你明确的功能做下面的代码,以清晰的价值。

this.user = { name: "" }; 
+0

感谢莫希特。这有效,但你能告诉我为什么我的代码不工作的原因吗? – Vishnu

+0

是的,实际上在Angular中,当你通过获取该元素来清除任何字段时,在这种情况下,ng-model被阻塞,然后双向绑定不起作用,这就是为什么它不工作。 –

1

清除这样的名字,

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

你并不需要一个明确的()方法在控制,只需要在角的双重结合的优势,用户名设置为空当你点击按钮时,字符串会被更新。

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

谢谢Karim。但是,你能告诉我为什么我的上面的代码不工作的原因吗? – Vishnu

+0

嗯,我只是不认为这是使用角度的正确方法。有了角度,你不应该以这种方式操纵dom,以避免与原生javascript混淆,但使用提供的工具。欢呼 – Karim

1

变化功能明确该代码

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

@Bamnaam,你还可以告诉OP他需要这样做的原因吗? Stackoverflow中的答案意味着非常清晰和描述性。所以记住这一点。 –