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 ===''))。現在代碼正常工作。 –