0

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

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

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...
      }
};

or

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

Imagine ngModelInput = "dateFilterInput"

How to translate this :

$scope.ngModelInput (How to write it ?)

to make this :

$scope.dateFilterInput 

Hope you see what I mean ^^

Thanks for your help !

Emidomenge
  • 1,172
  • 17
  • 26

1 Answers1

1

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.

SSG
  • 66
  • 2
  • Yes this is the solution that I was looking for ! Thanks for the tips also @SSG ! – Emidomenge May 20 '16 at 09:18
  • @SSG what if we have $scope.something.abc what would be the equivalent if something is not dynamic and abc is. And respectively if both are dynamic,I get error Unexpected token [ when only abc is dynamic – NeverGiveUp161 Mar 15 '18 at 13:37