2016-04-24 32 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從來沒有工作,因爲它返回迭代回調的結果。

相關問題