简体   繁体   English

检查重复项无法正常工作的功能

[英]Function that Checks for Duplicates not Working Properly

I have this mini app that allows the user to enter the make and model of a car, then adds it to the table below. 我有这个迷你应用程序,允许用户输入汽车的制造商和型号,然后将其添加到下表中。 I have added a function that will check for duplicates and alert if there are any already existing in the table. 我添加了一个函数,该函数将检查重复项并警告表中是否已有文件。 If there are no existing records that match, it will push the new "make" and "model" to the table. 如果没有匹配的现有记录,它将把新的“ make”和“ model”推到表中。 I changed the code to use _.isEqual instead of what I had prior and now it gets caught at the Alert every time I run it. 我将代码更改为使用_.isEqual而不是以前的代码,现在每次运行它时都会在Alert中捕获该代码。 Anyone know what is going on? 有人知道发生了什么吗?

 <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>

 var carsApp = angular.module('carsApp', []);

carsApp.controller('carController', function ($scope){

   $scope.cars = [];

  $scope.add = function () {

      var newCar = {
        make: $scope.make,
        model: $scope.model
      };

      function hasDuplicates(){
        angular.forEach($scope.cars, function(car, key){
          _.isEqual(car, newCar);
        });
      }

      if (hasDuplicates) {
          alert("Car already exists");
          } else {  
           $scope.cars.push(newCar);
          }
      }      

      $scope.rowClick = function(car){
          $scope.make= car.make;
          $scope.model= car.model;
      };

        $scope.make = null;
        $scope.model = null;

  });

Ended up going with a simpler option and used angular.equals instead. 最终得到了一个更简单的选项,并改用了angular.equals。 isEqual was too much of a pain to implement properly. isEqual很难正确实施。 Thanks for all the help! 感谢您的所有帮助!

function hasDuplicates(newCar){
     var returnVal = false;
     angular.forEach($scope.cars, function(car, key){
        if (angular.equals(car, newCar))
        {
          returnVal = true;
        }
      });
     return returnVal;
  };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM