AngularJs Remove duplicate elements in ng-repeat

前端 未结 5 1020
醉话见心
醉话见心 2020-11-30 01:43

I have one dictionary which is stored in field_detail

  • {{field.displayName}}
  • 5条回答
    •  南方客
      南方客 (楼主)
      2020-11-30 02:25

      I get a ticket saying when the user clicks save they get an error saying Unique Constraint violation, blah blah.. They want my screen to show them duplicates before the database enforces the constraint. So I wrote a function to loop through all instances of the array of objects and count the instances of it.

      $scope.anyDuplicates = function () {
          var dupes = false;
          for (var i = 0; i < $scope.kpiList.length; i++) {
              $scope.kpiList[i].cnt = 0;
      
              for (var j = 0; j < $scope.kpiList.length; j++) {
      
                  if ($scope.kpiList[i].description == $scope.kpiList[j].description) {
                      $scope.kpiList[i].cnt++;
                  }
      
                  if ($scope.kpiList[i].cnt > 1) dupes = true;
              }
          }
          return dupes;
      }
      

      ...and I use this function in my script to prevent the save, like this:

      if ($scope.anyDuplicates()) { 
         alert('Duplicates Detected.  Please remove the duplicates before pressing the save button.'); 
      } else { 
         save();
      }
      

      ...and to show the user as soon as they add a new record, like this:

      $scope.kpiList.push({kpiId: newId, description: newDescription, new: true});
      $scope.anyDuplicates();
      

      ... and then in my HTML I have something to tell the user where the duplicate is...

      
      
         
            duplicate
         
      
      ...
      
      

      Yes, I'm intentionally comparing each instance to itself. There's less code that way. I check to see if .cnt > 1 instead of > 0.

      Also to take note of... the kpiList.cnt field doesn't exist until the function runs for the first time. The ng-show="row.cnt > 1" will indicate a false (not truthy) and will not display until row.cnt has a value.

      Also, you should use a StyleSheet to format your span instead of putting it in the style attribute.

    提交回复
    热议问题