Search code examples
arraysangularjsvalidationis-empty

Angularjs show validation if one or more value is empty in the array


I have an angularjs sample here where I used ng-repeat as

<div ng-app="Test">
    <div ng-controller="TestController">
        <div ng-repeat="str in myData">{{str.id}}. {{str.string}}</div>
        <br/> <span ng-if="myData.length > 1" style="color:red;">One or more string is empty</span>
    </div>
</div>

to draw the list from an array. I want to show an validation if there are one or more value pf string in the array is empty. How can I achieve it?


Solution

  • You can iterate the array in your controller and increment a variable say count when your string is empty. Based on that count value you can manage your UI elements.

    For Example: In you controller:

        $scope.count = 0;
        for(var i = 0; i < $scope.myData.length; i++){
            if($scope.myData[i].string === ""){
                $scope.count ++;
            }
        }
    

    In you HTML:

        <div ng-repeat="str in myData">{{str.id}}. {{str.string}}</div>
        <br/> 
        <span ng-if="count >= 1" style="color:red;">One or more string is empty</span>
        </div>
    

    Hope it helps.