AngularJs推送功能验证无法正常工作

时间:2017-06-20 23:30:56

标签: javascript angularjs html5



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>
&#13;
&#13;
&#13; 嗨!我需要一些帮助。当我点击“添加项目”时,无论如何都会添加一个新对象,if (newItem !== 'undefined' || newItem !== '')。我的代码只是进入if并且我不知道为什么。 missingNewItemError也没有显示任何内容。请给我一个解决这个问题的方法。谢谢 !

2 个答案:

答案 0 :(得分:0)

这是因为您正在使用undefined的字符串文字并与三等号比较器进行比较。

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

当您使用被称为严格比较器的!==运算符时,它意味着与!=不同的运算符。只有当字符串为空或newItem变量是字符串'undefined'而不是undefinednewItem只是一个空字符串时,才会触发此操作。

将其更改为:

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

或者,如果您想保存更多代码,因为空字符串的计算结果为falsey而非空字符串的结果为truthy

if (newItem)

可以找到JavaScript中的等式比较参考here

答案 1 :(得分:0)

Angular为验证创建一些默认函数<input id="someInput" type="text" /> <button id="btnValidate" type="button" onclick="validate()">Validate</button>defined等等......

作为此示例,您可以使用undefined来检查您的媒体资源验证

angular.isUndefined

或者您可以创建新的自定义验证并将其指定为角度

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

您可以使用它来检查angular.isUndefinedOrNull = function (val) { return angular.isUndefined(val) || val === "" || val === null; } null

undefined