Faizah Pratiwi Faizah Pratiwi - 1 month ago 15
AngularJS Question

How to show id with angularjs

I want to show id with pop up when i click button delete. but when i click the delete button, it doesnt work. when i check the console in inspect element, they say listData not undefined. Anyone help me please? i'm new in angularjs
view :

<!DOCTYPE html>
<html>
<head>
<title>CRUD</title>
<style type="text/css">
.table{
border-collapse: collapse;
}

tr,td,th{
border: 1x solid #000;
padding: 5px;
}

td{
width: 300px
}
</style>
</head>
<body ng-App="myAPP">
<div ng-controller="MainController">
<table class="table">
<tr>
<th>ID</th>
<th>Nama</th>
<th>Alamat</th>
<th>Action</th>
</tr>
<tr ng-repeat="x in listData">
<td>{{x.id}}</td>
<td>{{x.nama}}</td>
<td>{{x.alamat}}</td>
<td>
<a href="#" ng-click="del(x.id)">Delete</a>
<a href="#" ng-click="update(x.id)">Edit</a>
</td>
</tr>
</table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.6/angular.min.js"></script>
<script src="js/app.js"></script>
<script src="controller/MainController.js"></script>
</body>
</html>


controller :

app.controller('MainController',['$scope',function($scope){
$scope.listData = [
{
'id' : 01,
'nama' : 'Faizah Pratiwi',
'alamat' : 'Malang'
},
{
'id' : 02,
'nama' : 'Anastasya Putri',
'alamat' : 'Jember'
},
{
'id' : 03,
'nama' : 'Sharon Natalia',
'alamat' : 'Tulungagung'
},
{
'id' : 04,
'nama' : 'Faizah Pratiwi',
'alamat' : 'Malang'
},
];

$scope.del = function(id){
var index = getSelectedIndex(id);
alert(index);
$scope.listData.slice(index,1);
};
function getSelectedIndex(id){
for (var i = 0; i < listData.length; i++) {
if($scope.listData[i].id==id)
return i;
return -1;
}
}
}]);

Answer

It says undefined because, It should be $scope.listData,

 function getSelectedIndex(id){
        for (var i = 0; i < $scope.listData.length; i++) {
            if($scope.listData[i].id==id)
                return i;               
        }
        return -1;
    }

Also it's not slice, it is splice

$scope.listData.splice(index, 1);

Rather than doing that you can directly delete the index from array with this piece of code,

$scope.del = function(index) {
    alert(index);
    $scope.listData.splice(index, 1);
  };

Demo

DEMO WITH STRAIGHT FUNCTION