角度拼接功能删除另一个记录而不是实际选择的记录

时间:2016-02-02 16:08:24

标签: javascript angularjs

angular splice函数删除另一条记录而不是实际选择的记录。请找到下面的代码。

在下面的演示代码中,删除pat记录,代码将删除Max记录。请查看以下代码

function CustomerController($scope) {
    $scope.list = [
        { ID:"1", FirstName: 'Bharani', LastName: 'Kumar', City: 'New Delhi' },
        { FirstName: 'Pat', LastName: 'J', City: 'Paris' },
        { FirstName: 'John', LastName: 'P', City: 'Washington DC' },
        { FirstName: 'Max', LastName: 'X', City: 'London' }
    ];
 
	$scope.delCustomer = function (FirstName) {
	     var index = $scope.list.indexOf(FirstName);
		 $scope.list.splice(index, 1); 
    };
}
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
</head>
<body>
    <div data-ng-controller="CustomerController">
        <ul>
            <li ng-repeat="item in list | filter:FirstNameSearch | orderBy:'FirstName':false">{{ item.FirstName +"  , "+ item.LastName +"  , "+ item.City}}      &nbsp;&nbsp;<a ng-click="delCustomer(item.FirstName)">Delete</a></li>
        </ul>
	</div>
    <script src="CustomerController.js"></script>
</body>
</html>

1 个答案:

答案 0 :(得分:2)

您必须发送记录而不是仅仅将FirstName发送到函数,它将尝试将第一个名称与记录数组匹配,它将始终返回-1作为索引。

function CustomerController($scope) {
    $scope.list = [
        { ID:"1", FirstName: 'Bharani', LastName: 'Kumar', City: 'New Delhi' },
        { FirstName: 'Pat', LastName: 'J', City: 'Paris' },
        { FirstName: 'John', LastName: 'P', City: 'Washington DC' },
        { FirstName: 'Max', LastName: 'X', City: 'London' }
    ];
 
	$scope.delCustomer = function (FirstName) {
	     var index = $scope.list.indexOf(FirstName);
		 $scope.list.splice(index, 1); 
    };
}
<!DOCTYPE html>
<html ng-app>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js">
</script>
</head>
<body>
    <div data-ng-controller="CustomerController">
        <ul>
            <li ng-repeat="item in list | filter:FirstNameSearch | orderBy:'FirstName':false">{{ item.FirstName +"  , "+ item.LastName +"  , "+ item.City}}      &nbsp;&nbsp;<a ng-click="delCustomer(item)">Delete</a></li>
        </ul>
	</div>
    <script src="CustomerController.js"></script>
</body>
</html>