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.
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.
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);
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];
}
}
};
I would like to know if there is any easy way (like a directive) in AngularJS to do the action in PART 1 automatically.
source
to share