Whenever a make and model are added using the "add" button, I need to ensure that there are no duplicates. If a duplicate is found, an alert should be displayed, and the entry should not be added to the table. Unfortunately, I have been unable to find a solution for this issue...
Below is the complete code for the beginner project I am currently working on. I apologize in advance if this post is unclear, as this is my first time posting here. Thank you all for your help.
<div>
<div>Make: <input type="text" ng-model="make"></div>
<div>Model:<input type="text" ng-model="model"></div>
<button ng-click="add()">Add</button>
<tr>
<th>Make</th>
<th>Model</th>
</tr>
<tr ng-repeat="car in cars" ng-click="rowClick(car)">
<td>{{car.make}}</td>
<td>{{car.model}}</td>
</tr>
<table class="table carsTable">
<tr>
<th>Make</th>
<th>Model</th>
</tr>
<tr ng-repeat="car in cars" ng-click="rowClick(car)">
<td>{{car.make}}</td>
<td>{{car.model}}</td>
</tr>
<script>
var carsApp = angular.module('carsApp', []);
carsApp.controller('carController', function ($scope){
$scope.cars = [];
$scope.add = function () {
// Check for duplicates
var isDuplicate = false;
$scope.cars.forEach(function(item){
if (item.make === $scope.make && item.model === $scope.model) {
isDuplicate = true;
return;
}
});
if(isDuplicate){
$scope.alert();
} else {
$scope.cars.push({
make: $scope.make,
model: $scope.model
});
$scope.make = null;
$scope.model = null;
}
};
$scope.rowClick = function(car){
$scope.make = car.make;
$scope.model = car.model;
};
$scope.alert = function(){
alert('Already exists in table');
};
});