如果文本框为空,则显示div(ng-repeat)

时间:2016-04-24 02:21:53

标签: javascript arrays angularjs foreach

在我的应用程序中,我正在创建一个这样的对象:

$scope.editphonenumbers = [];

在ng-click上,将对象推送到它:

$scope.addEditPhone = function(){
    var person = {
        phoneno: "",
        name : ""
    };
    if($scope.editphonenumbers.length<3){
        $scope.editphonenumbers.push(person);
    }
    }; 

此电话号码将以ng-repeat显示:

<div  class="relativeWrap" ng-repeat="phone in editphonenumbers">
       <input placeholder="Phone Number" pattern="[0-9]{10}" ng-maxlength="10" maxlength="10" type="text" name="phonenumber[]" ng-model="phone.phoneno" >
                </div>

现在我需要显示一个div,如果任何一个文本框都是空的。

我尝试了以下内容:

<div ng-show="checkPhoneSS();">Phone Number is Mandatory</div>

$scope.checkPhoneSS=function(){
        angular.forEach($scope.editphonenumbers, function(item) {
            if(item.phoneno==""){
                return true;
            }
        });
        return false;
    };

但是这种方法多次触发并且显示的不仅仅是实际数据。

2 个答案:

答案 0 :(得分:0)

使用常规for循环,您将立即突破它:

var item;
for(var i=0,size=$scope.editphonenumbers.length; i<size; i++){
  item = $scope.editphonenumbers[i];
  if(item.phoneno=="") return true;
  return false;
};

forEach很方便但是你可以突破它,直到它遍历整个集合并且每次迭代都调用回调。

另外我的猜测是你的示例return true永远不会工作,因为它返回迭代回调的结果。

答案 1 :(得分:0)

从我所看到的你使用angular.forEach错误。你不应该从它返回任何东西,因为你实际上不能(它是为迭代数组或对象而设计的,并且总是返回你作为参数提供的对象的引用。

<div ng-show="checkPhoneSS()">Phone Number is Mandatory</div>

$scope.checkPhoneSS = function () {
    return $scope.editphonenumbers.some(function (item) {
        return !item.phoneno || item.phoneno === '';
    });
};

为什么这样更好? 它使用本机一些实现来测试数组中任何值是否通过函数中传递的测试。

这意味着如果 $ scope.editphonenumbers 中的任何值将 phoneno 字段设置为空(或未定义),则它将返回true。如果没有,那么某些结果将是假的。

相关问题