Emidomh Emidomh - 5 months ago 25x
AngularJS Question

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

I have a form containing inputs with a ng-model defined for each of them :

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

As my form could get dynamically further inputs (using ng-repeat), I want to check in each input if the value is empty using ng-model dynamically

I'm doing a foreach loop for each inputs in the form, and calling this function with the ng-modal name (string) as parameter :

$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...

But this doesn't work because ngModelInput is a string.

For example :

ngModelInput = "dateFilterInput"

How to translate this :

(How to write it ?)

to make this :


Hope you see what I mean ^^

Thanks for your help !


Modify the isEmpty function as below and that should solve your problem. Do not use ng as prefix to any variable as ng is a angular reserved keyword and it may confuse other developers.

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

The above code takes whatever the parameter(string) you pass to the isEmpty function and checks for that particular name in the $scope object and gives you the value based on it.