Angular / Ionic:无法在html输入字段中访问值

时间:2016-06-09 15:20:33

标签: javascript angularjs ionic-framework

我有以下HTML代码:

        <div class="list">
            <label class="item item-input">
                <input id="email" ng-model="email" type="text" placeholder="Email Address">
            </label>
            <br> 
            <center>
            <button class="button button-positive" ng-click="getData();"> Test </button>
             </center>
        </div>

以下Angular代码:

    $scope.getData = function() {
        var emailadd = document.getElementById('email');
        var url = "http://172.16.99.138/sendemail.php?emailaddress="+emailadd;
        console.log(url);
    };

但是当我尝试运行代码时,控制台说它无法找到变量。非常感谢这里的指导。

2 个答案:

答案 0 :(得分:2)

注意:您的代码无论如何都是错误的,因为document.getElementById('email')会获得dom元素,这不是元素的value()

你应该这样做“Angular Way”:

您需要在控制器中定义模型,如下所示:

  $scope.email = {
    text: ''
  };

然后你可以像这样绑定HTML:

<input type="email" name="input" ng-model="email.text" required>

然后您可以在方法中使用$scope.email

$scope.getData = function() {
   var url = "http://172.16.99.138/sendemail.php?emailaddress="+$scope.email.text;
   console.log(url);
};

ng-model Documentation

答案 1 :(得分:1)

在AngularJs中使用这种数据绑定方式,将电子邮件作为函数getData()

中的参数传递
<div class="list">
            <label class="item item-input">
                <input id="email" ng-model="email" type="text" placeholder="Email Address">
            </label>
            <br> 
            <center>
            <button class="button button-positive" ng-click="getData(email);"> Test </button>
             </center>
        </div>

在您的控制器中

  $scope.getData = function(email) {
       // var emailadd = document.getElementById('email');don't use this
        var url = "http://172.16.99.138/sendemail.php?emailaddress="+email;
        console.log(url);
    };