2017-06-20 29 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))