I tried to execute a simple function with AngularJS as shown below. In the product list, when the ...">

Problem with <select ng-options = "..." / ">

I tried to execute a simple function with AngularJS as shown below. In the product list, when the user clicks an item and clicks the "Delete" button, the item will be removed.

enter image description here

HTML:

<div ng-app="app" ng-controller="MainController">
    <div>
      <select ng-options="item.name for item in items" ng-model="currentItem" size="5" style="width: 200px"></select>
    </div>
    <button ng-click="removeItem()">Remove</button>
  </div>

      

and the script looks like this:

angular.module('app', [])
  .controller('MainController', function($scope) {
    $scope.items = [{
      name: 'item1'
    }, {
      name: 'item2'
    }, {
      name: 'item3'
    }];

    $scope.currentItem = $scope.items[0];

    $scope.removeItem = function() {
      var index = $scope.items.indexOf($scope.currentItem);
      $scope.items.splice(index, 1);
    };

  });

      

The problem is that when I tried to remove an item (i.e. item2), the list always shows an empty item at the first position. When I click "item1" or "item3" the empty item disappears.

enter image description here

I know this is called ng-model="currentItem"

in the html. The element that currentItem points to deletion, currentItem points to null. So I decided to change the removeItem function as shown below to solve this problem.

$scope.removeItem = function() {
      var index = $scope.items.indexOf($scope.currentItem);
      $scope.items.splice(index, 1);

      /* PART 1 begin */
      if ($scope.items.length === 0) {
        $scope.currentItem = null;
      } else {
        if (index >= 0 && index <= $scope.items.length - 1) {
          $scope.currentItem = $scope.items[index];
        } else {
          $scope.currentItem = $scope.items[$scope.items.length - 1];
        }
      }
      /* PART 1 end */
    };

      

I would like to know if there is any easy way (like a directive) in AngularJS to do the action in PART 1 automatically.

+3


source to share


1 answer


There is a simple way by which you can prevent the inclusion of only

 <option value="" ng-show="false"></option>

      

in selection as below

<select ng-options="item as item.name for item in items" ng-model="currentItem" size="5" style="width: 200px">
   <option value="" ng-show="false"></option>
</select>

      

Working demo



UPDATE 1

I solved the problem by not highlighting the last item, see a working demo

$scope.removeItem = function () {
    var index = $scope.items.indexOf($scope.currentItem);
    $scope.items.splice(index, 1);
    index === $scope.items.length ? $scope.currentItem = $scope.items[index - 1] : $scope.currentItem = $scope.items[index];
};

      

Working demo

+4


source







All Articles