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
には何も表示されません。この問題の解決策を教えてください。ありがとうございました !
回答ありがとうございますが、まだ動作しません。あなたは「未定義」の間違いについて正しいものでした。私は解決策を見つけました:(!(newItem === undefined || newItem === '')))。今すぐコードが正しく動作します。 –