AngularJS 如何动态获取表单或其他输入的 ng-model 值

AngularJS How to dynamically get the ng-model value of inputs in a form or whatever

我有一个包含输入的表单,其中每个输入都定义了一个 ng-model :

<form>
<input type="date" ng-model="dateFilterInput" id="dateFilter" class="...">
<select class="..." id="authorFilter" ng-model="authorFilterInput">   
...
</select>
<input type="text" class="..." id="categoryFilter" ng-model="categoryFilterInput">
</form>

由于我的表单可以动态获取更多输入(使用 ng-repeat),如果值为空,我想检查每个输入 动态使用 ng-model

我正在为表单中的每个输入执行一个 foreach 循环,并使用 ng-modal 名称(字符串)作为参数调用此函数:

$scope.isEmpty = function(ngModelInput) {
      if(modelInput == "" || typeof modelInput == 'undefined') {
        //do something if field is empty...
      }
};

$scope.isEmpty = function(ngModelInput) {
      if($scope.modelInput == "" || typeof $scope.modelInput == 'undefined') {
        //do something if field is empty...
      }
};

但这不起作用,因为 ngModelInput 是一个字符串。

例如:

想象一下ngModelInput = "dateFilterInput"

如何翻译:

$scope.ngModelInput(怎么写?)

做这个:

$scope.dateFilterInput 

希望你明白我的意思^^

感谢您的帮助!

如下修改isEmpty函数应该可以解决你的问题。 不要使用 ng 作为任何变量的前缀,因为 ng 是 angular 保留关键字,它可能会使其他开发人员感到困惑。

$scope.isEmpty = function(modelInput) {
      if($scope[modelInput] == "" || typeof $scope[modelInput] == 'undefined') {
        //do something if field is empty...
      }
};

以上代码采用您传递给 isEmpty 函数的任何参数(字符串)并在 $scope 对象中检查该特定名称并根据它为您提供值。