2017-06-20 7 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という文字列リテラルを使用しており、3つの等号コンパレータと比較しているからです。

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

あなたは厳格なコンパレータと呼ばれ、それが!=に別の何かを意味しています!==演算子を使用します。これは、文字列が空であるか、の代わりに変数が文字列'undefined'であるか、またはnewItemが空の文字列である場合にのみトリガーされます。

変更と:

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

それとも、空の文字列が等価比較のための参照をfalseyに評価し、truthy

if (newItem) 

に非空の文字列のため、より多くのコードを保存したい場合JavaScriptの場合はhereとなります。

+0

回答ありがとうございますが、まだ動作しません。あなたは「未定義」の間違いについて正しいものでした。私は解決策を見つけました:(!(newItem === undefined || newItem === '')))。今すぐコードが正しく動作します。 –

0

角度あなたがあなたの財産

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

の検証をチェックするためにangular.isUndefinedを使用することができ、このサンプルとして

...などdefinedまたはundefinedとして検証にいくつかのデフォルトの関数を作成するか、作成することができます新しいカスタム検証を角度に割り当てる

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

をチェックすることができますとundefined

if (angular.isUndefinedOrNull(newItem)) 
関連する問題