2017-06-20 32 views
0

AngularJs推功能驗證工作不正常

angular.module('app', []) 
 
.controller('gListCtrl', function ($scope) { 
 
     $scope.groceries = [ 
 
      { item: 'Tomatoes', purchased: false }, 
 
      { item: 'Potatoes', purchased: false }, 
 
      { item: 'Bread', purchased: false }, 
 
      { item: 'Hummus', purchased: false }, 
 

 
     ]; 
 
     $scope.addItem = function (newItem) { 
 
      if (newItem !== 'undefined' || newItem !== '') { 
 
       $scope.groceries.push({ 
 
        item: newItem, purchased: false 
 

 
       }); 
 
       $scope.missingNewItemError = ''; 
 

 
      } else { 
 
       $scope.missingNewItemError='Please enter an item' 
 

 
      } 
 

 

 
     } 
 
    })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<html ng-app="app"> 
 
<head> 
 
    
 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> 
 
    <link rel="stylesheet" href="app.css"/> 
 
    
 
    
 
    
 
    
 
</head> 
 
<body> 
 
    <div ng-controller="gListCtrl"> 
 
     <h3>Grocery List</h3> 
 
     <table> 
 
      <thead> 
 
       <tr> 
 
        <th>Item</th> 
 
        <th>Purchased</th> 
 
       </tr> 
 
      </thead> 
 
      <tr ng-repeat="grocery in groceries"> 
 
       <td>{{grocery.item}}</td> 
 
       <td> 
 
        <input type="checkbox" ng-model="grocery.purchased" /> 
 
       </td> 
 
      </tr> 
 
     </table> 
 
     <br /> 
 
     <label>New Item : 
 
     <input type="text" ng-model="newItem"/> 
 

 
     </label> 
 
     <button ng-click="addItem(newItem)">add item</button> 
 
     <h4>{{missingNewItemError}}</h4> 
 

 
    </div> 
 
    <script src="app.js"> 
 

 
    </script> 
 
</body> 
 
</html>
嗨!我需要一些幫助。當我點擊'添加項目'時,它會添加一個新的對象,無論如何不應該發生 if (newItem !== 'undefined' || newItem !== '')。我的代碼剛剛插入 if,我不知道爲什麼。此外, missingNewItemError不顯示任何內容。請給我一個解決這個問題的方法。謝謝 !

回答

0

這是因爲您正在使用undefined的字符串文字並與三等號比較器進行比較。

if (newItem !== 'undefined' || newItem !== '') 

當您使用!==運營商這就是所謂嚴格的比較,這意味着東西!=不同。這隻會在字符串爲空或newItem變量爲字符串'undefined'而不是undefinednewItem只是一個空字符串時觸發。

修改成:

if (newItem !== undefined || newItem !== '') 

或者,如果你想從一個空字符串的計算結果爲falsey和非空字符串truthy

if (newItem) 

一種平等的比較基準,以節省更多的代碼在JavaScript中可以找到here

+0

感謝您的回答,但仍然無法正常工作。你對「未定義」的錯誤是正確的。我找到了解決方案:(!(newItem === undefined || newItem ===''))。現在代碼正常工作。 –

0

角創建一個默認的一些功能,如驗證或definedundefined等等

因爲這個樣本可以使用angular.isUndefined來檢查你的財產

if (angular.isUndefined(newItem) || newItem !== '') 

的驗證,也可以創建新的自定義驗證並將其分配給角度爲

angular.isUndefinedOrNull = function (val) { 
    return angular.isUndefined(val) || val === "" || val === null; 
} 

您可以使用它來檢查nullundefined

if (angular.isUndefinedOrNull(newItem))