Angularjs: 如何在没有 ng-model 的情况下获取输入值

Angularjs: How to get value of input without ng-model

我需要通过 ng-repeat 进行一些输入,在我的 json 文件中,我的对象中有一个名为 name 的 属性,如下所示:

"url":"find_company",
    "values":[
      {
        "name":"company name",
        "type":"input_search"
      },{
        "name":"company_phone",
        "type":"input_search"
      }
    ]

我想在数据库中进行搜索,在搜索中您可以按任何字段或两个或多个字段查找。与对象的 属性 相同的字段调用。所以通过 ng-keyup 我需要发送到我的函数

search(field, value)

两个参数。我想做这样的事情

<div ng-repeat="value in param.values">
    <input ng-if="value.type == 'input_search'" 
           ng-keyup="search(value.name, this.text)" 
           type="text">

如何在不使用 ng-model 的情况下发送此输入的功能文本?其中 this.text 是输入值。

由于您使用的是 ng-keyup,因此您可以使用 $event.target.value 检索输入值。


评论:this适合像onclick这样的正常事件,但不适合angular

参考下面的例子。

angular.module("app", [])
  .controller("myCtrl", function($scope) {
    $scope.showValue = function(val) {
      alert(val);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
  <input type="test" ng-keyup="showValue($event.target.value)">
</div>

这就是你的做法 with ngModel:

<div ng-repeat="value in param.values">
    <input ng-if="value.type == 'input_search'" ng-model="value.val" ng-keyup="search(value)" type="text">

在你的控制器中:

$scope.search = function( item ) {
    console.log( item.val ); // Here you have the value using ngModel
    console.log( item.name ); // Here you have the "name" property of the element inside the loop
}

如您所见,您可以使用 ngModel 并通过将对象本身传递给函数,您可以从控制器中的函数访问其属性。

请注意,视图中有 this.text - 我不知道它到底是什么,所以我从示例中删除它以使事情更清楚,但您当然可以在您的代码中使用它。

我知道问题是 without using ng-model。但我怀疑您可能想要这个,因为您希望在发生数据绑定时进行自定义。如果是这种情况,您可以将 ng-model-optionsng-change:

一起使用
<input type="text" ng-model="yourModel" ng-model-options="{ updateOn: 'keyup' }" ng-change="search()" />

ng-change 在模型更新时触发,在本例中是在 keyup 之后。因此 yourModel 的值将在 search() 执行时是最新的。