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

标签 javascript angularjs angularjs-scope angular-ngmodel

我有一个包含输入的表单,其中每个输入都定义了一个 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 对象中的特定名称,并根据它为您提供值。

关于javascript - AngularJS 如何动态获取表单或其他形式输入的 ng-model 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37341745/

相关文章:

angularjs - ng-form 嵌套在 ng-switch 中

javascript - "type"是 JavaScript 中的关键字吗?

javascript - 为什么这个网站返回包装在 jQuery 标签中的自动完成数据?

javascript - Bootstrap 切换复选框在 ng-view 中不起作用

javascript - 将 Base64 图像字符串转换回文件以发送到 Parse upload

javascript - net::ERR_EMPTY_RESPONSE 尝试在 angularjs 指令中查找 css 文件时

javascript - 通过用户输入更改输入号码不起作用

javascript - 无法读取未定义错误的属性 'push'?

javascript - Uncaught ReferenceError : init is not defined

javascript - 显示、隐藏,然后重新显示布局中断事件