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;
if (newItem !== 'undefined' || newItem !== '')
。我的代码只是进入if
并且我不知道为什么。 missingNewItemError
也没有显示任何内容。请给我一个解决这个问题的方法。谢谢 !
答案 0 :(得分:0)
这是因为您正在使用undefined
的字符串文字并与三等号比较器进行比较。
if (newItem !== 'undefined' || newItem !== '')
当您使用被称为严格比较器的!==
运算符时,它意味着与!=
不同的运算符。只有当字符串为空或newItem
变量是字符串'undefined'
而不是undefined
或newItem
只是一个空字符串时,才会触发此操作。
将其更改为:
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