2016-04-24 61 views
0

在我的应用程序,我创建一个对象是这样的:显示一个div,如果文本框为空(NG-重复)

$scope.editphonenumbers = []; 

在NG单击,按下一个目标是这样的:

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

该电话号码将在NG-重复显示:

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

但这种方法烧制很多次,显示出比实际数据更个性化。

回答

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.editphonenumbersphoneno字段为空(或未定义),那么它将返回true。如果没有人的结果是假的。

+0

它的工作...谢谢 – ramesh

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从来没有工作,因为它返回迭代回调的结果。