【问题标题】:How do I get the value of a text field using AngularJS?如何使用 AngularJS 获取文本字段的值?
【发布时间】:2017-12-05 02:36:46
【问题描述】:

我想在提交表单时使用 AngularJS 获取文本字段值的值。

下面的代码总是显示“未定义”。

html:

<form ng-submit="AdvanceSearchSubmit($event)" name="AdvanceSearch" novalidate>
 <p ng-show="!AdvanceSearch.SearchKeyWord.$pristine && AdvanceSearch.SearchKeyWord.$invalid" class="text-danger">Text Cannot Be Empty!</p>
  <div ng-hide="AdvanceSearchModel" class="input-group">
    <input name="SearchKeyWord" ng-model="SearchKeyWord" id="SearchKeyWord" class="form-control" placeholder="Search in timeline...." type="text" required>
      <span class="input-group-btn" ng-click="isAdvanceSearch='false'; SearchPost(0,'true')">
       <button ng-disabled="AdvanceSearch.$invalid" type="submit" name="search" id="search-btn" class="btn btn-flat">
        <i class="fa fa-search"></i>
       </button>
      </span>
     </div>
</form>

一次尝试:

$scope.AdvanceSearchSubmit = function(event)
{
    alert(event.target.value);
};

又一次尝试:

$scope.AdvanceSearchSubmit = function(event)
{
    alert(event.SearchKeyWord.value);
};

【问题讨论】:

    标签: javascript angularjs forms angularjs-forms


    【解决方案1】:

    而不是event 传递SearchKeyWord 作为参数

    ng-submit="AdvanceSearchSubmit(SearchKeyWord)"
    

    控制器

    $scope.AdvanceSearchSubmit = function(keyWord)
    {
        alert(keyWord);
    };
    

    【讨论】:

      【解决方案2】:

      您根本不需要在提交时将事件传递给您的AdvanceSearchSubmit。您已经在$scope 中提供了您的值,例如ng-model,用于输入字段,例如ng-model="SearchKeyWord"

      alert($scope.SearchKeyWord); //access value from `$scope` directly
      

      【讨论】:

      • 为什么 event.SearchKeyWord.value 不起作用你能解释一下吗????
      • @nayanchowdhury 我并不是说这是不可能的,您可以通过在您的函数中执行 console.log($(event.target).serializeArray()) 来检索表单值。但是根本不需要这样做,AngularJS 为您提供了很棒的数据绑定功能,可以跟踪您的模型并在用户更改值时更新值。更好的是,您应该将 model 传递给 submit 方法并将该数据发送到 API ..
      猜你喜欢
      • 2011-08-02
      • 2015-06-24
      • 2012-07-18
      • 1970-01-01
      相关资源
      最近更新 更多