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

风流意气都作罢 提交于 2019-12-12 01:28:55

问题


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?


回答1:


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.




回答2:


just initialize $scope.count=0 now you can perform your task.....

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


来源:https://stackoverflow.com/questions/33857161/angularjs-show-validation-if-one-or-more-value-is-empty-in-the-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!