My task is to display a table using ng-repeat, say for eg: 1234567 with a button on each row. On click of the button, I want to display an alert with the corresponding number.
The following is my HTML file.
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="myApp.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="x in records">
<td>{{x.Digit}}</td>
<td><input type="button" value="Press Me" ng-click="test(record)" /></td>
</tr>
</table>
</body>
</html>
<html>
<body>
JS file.
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
// $scope.records = [1,2,3,4,5,6,7];
$scope.records = [
{
"Digit" : "1",
},
{
"Digit" : "2",
},
{
"Digit" : "3",
},
{
"Digit" : "4",
},
{
"Digit" : "5",
},
{
"Digit" : "6",
},
{
"Digit" : "7",
}
]
$scope.test = function(text) {
alert("You clicked");
// alert(text);
}
// }).directive('li',function(){
// return {
// template: '<records> <record ng-click="test(record)" ng-repeat="record in records"> {{ record }} </record></br></records> '
// }
// });
// app.controller("myCtrl", function($scope) {
// $scope.myFunction = function(text){
// alert(text);
// };
});
Since your iterator is x, So pass x.digit, not record.
<tr ng-repeat="x in records">
<td>{{x.Digit}}</td>
<td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td>
</tr>
you need to pass x not record
<tr ng-repeat="x in records">
<td>{{x.Digit}}</td>
<td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td>
</tr>
DEMO
var app = angular.module("myApp", []);
app.controller('myCtrl', function($scope) {
// $scope.records = [1,2,3,4,5,6,7];
$scope.records = [
{
"Digit" : "1",
},
{
"Digit" : "2",
},
{
"Digit" : "3",
},
{
"Digit" : "4",
},
{
"Digit" : "5",
},
{
"Digit" : "6",
},
{
"Digit" : "7",
}
]
$scope.test = function(text) {
alert("You clicked "+ text);
}
});
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
<table>
<tr ng-repeat="x in records">
<td>{{x.Digit}}</td>
<td><input type="button" value="Press Me" ng-click="test(x.Digit)" /></td>
</tr>
</table>
</body>
</html>
<html>
<body>
Related
I have a list that shows the total of the records, when filtering a single name it still shows me the total of the records and not the total of the filtered record. TRY HERE
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
name:
<input type="text" ng-model="model_filter">
<hr/>
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in records | filter: model_filter">
<td>{{x.Name}}</td>
<td>{{x.Money | currency}}</td>
</tr>
<tr>
<td>TOTAL</td>
<td>{{Total | currency}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.records = [
{
"Name": "Rodrigo",
"Money": 10
},
{
"Name": "Rodrigo",
"Money": 25
},
{
"Name": "Arnodl",
"Money": 15
},
{
"Name": "Carlos",
"Money": 5
}
]
$scope.Total = 0;
for (var i = 0; i < $scope.records.length; i++) {
$scope.Total += $scope.records[i].Money;
}
});
</script>
</body>
</html>
RESULT:
WITH FILTER:
MY PROBLEM
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp">
name:
<input type="text" ng-model="model_filter">
<hr/>
<table ng-controller="myCtrl" border="1">
<tr ng-repeat="x in records | filter: model_filter">
<td>{{x.Name}}</td>
<td>{{x.Money | currency}}</td>
</tr>
<tr>
<th>TOTAL</th>
<td>{{Total()}}</td>
</tr>
<tr>
<th>TotalFiltered</th>
<td>{{ TotalFiltered() }}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.records = [{
"Name": "Rodrigo",
"Money": 10
},
{
"Name": "Rodrigo",
"Money": 25
},
{
"Name": "Arnodl",
"Money": 15
},
{
"Name": "Carlos",
"Money": 5
}
]
$scope.Total = () => $scope.records.reduce((total, b) => total + b.Money, 0);
$scope.TotalFiltered = () => {
return $scope.records.reduce((total, b) => {
if ($scope.model_filter && b.Name.toUpperCase().includes($scope.model_filter.toUpperCase())) { return total + b.Money; }
else { return total; }
}, 0);
}
});
</script>
</body>
</html>
To achieve expected result , use below option
Use scope variabled for filtered values
ng-repeat="x in filteredValues = (records | filter: model_filter)"
2.Use ng-keyup to get filtered values on input field
<input type="text" ng-model="model_filter" ng-keyup="calcTotal($event)">
3. In Key up event, calculate total again with filtered values
$scope.calcTotal = function(e){
$scope.Total = 0;
for (var i = 0; i < $scope.filtered.length; i++) {
$scope.Total += $scope.filtered[i].Money;
}
}
codepen - https://codepen.io/nagasai/pen/KjPrvr
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
name:
<input type="text" ng-model="model_filter" ng-keyup="calcTotal($event)">
<hr/>
<table border="1">
<tr ng-repeat="x in filteredValues = (records | filter: model_filter)">
<td>{{x.Name}}</td>
<td>{{x.Money | currency}}</td>
</tr>
<tr>
<td>TOTAL</td>
<td>{{Total | currency}}</td>
</tr>
</table>
<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function ($scope) {
$scope.calcTotal = function(e){
$scope.Total = 0;
for (var i = 0; i < $scope.filteredValues.length; i++) {
$scope.Total += $scope.filteredValues[i].Money;
}
}
$scope.records = [
{
"Name": "Rodrigo",
"Money": 10
},
{
"Name": "Rodrigo",
"Money": 25
},
{
"Name": "Arnodl",
"Money": 15
},
{
"Name": "Carlos",
"Money": 5
}
]
$scope.Total = 0;
for (var i = 0; i < $scope.records.length; i++) {
$scope.Total += $scope.records[i].Money;
}
});
</script>
</body>
</html>
Issue from your code:
Calculating total on $scope.records which remains same always event with filter and without filter
Total is getting calculated on intial load with $scope.records and not with filter
I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/site.css" />
<!--<script src="js/script.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p ng-model="array"></p>
<input type="text" ng-model="product" />
<table>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Image</th>
</tr>
<tr ng-repeat="product in products">
<td>{{ product.name }}</td>
<td>{{ product.description }}</td>
<td>{{ product.price }}</td>
<td>{{ product.image }}</td>
</tr>
</table>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl',
function callController($scope) {
fetch('js/adds.json').then(function (response) {
return response.json();
}).then(function (data) {
var jproducts = data["products"];
for (var i = 0; i < jproducts.length; i++) {
$scope.products = [
{
name: jproducts[i]["name"],
description: jproducts[i]["description"],
price: jproducts[i]["price"],
image: jproducts[i]["image"]
}
];
}
});
});
</script>
</div>
</body>
</html>
And here is the JSON file:
{
"products" : [
{ "name" : "Porsche Bike", "description" : "A bike with a brand name!", "price" : 10000, "image" : "bike.jpg" },
{ "name" : "Pretty Shoes", "description" : "Come to our shoe store", "price" : 54.45, "image" : "shoes.jpg" },
{ "name" : "Pie Fest!", "description" : "Oh yeah this is officially the best pie ever", "price" : 3.45, "image" : "pie.jpg" },
{ "name" : "Inside Out Umbrella", "description" : "Designer Umbrellas for low cost", "price" : 14.55, "image" : "umbrella.jpg" },
{ "name" : "Coffee", "description" : "Come get your morning dessert", "price" : 4.59, "image" : "coffee.jpg" }
]
}
What I need is for the JSON to be displyed into a table. However, so far it only displays this:
Coffee Come get your morning dessert 4.59 coffee.jpg
How can I get it to display all the products? And also it only displays something when I type something into the text input.
You do not have to iterate over producs inside the controller. Simply assign it as
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get('adds.json').
then(function(response) {
$scope.products = response.data.products;
});
});
DEMO
Here's my code:
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller('MyCtrl', ['$scope', MyCtrl]);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.names = [
{
"name": "AAAAAA",
"down": "False"
},
{
"name": "BBBBBB",
"down": "45%"
},
{
"name": "CCCCC",
"down": "12%"
}
];
$scope.datas = [
{
"data": "AAAAAA/45%"
}
];
$scope.getTheRightData = data => $scope.datas.map(d=>d.data.split('/')[0]).find(d=>d===data);
}
HTML
<div ng-controller="MyCtrl">
<table>
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.down}}</td>
<td ng-bind="getTheRightData(name.name)"></td>
</tr>
</tbody>
</table>
What i do : one element from $scope.datas will match an element in $scope.names, but it only shows when name.name is the same. I need when name.name and name.down is the same, something like this : <td ng-bind="getTheRightData(name.name,name.down)"></td>, and in controller
$scope.getTheRightData = data => $scope.datas.map(d=>d.data.split('/')[0][1]).find(d=>d===data);
}
, but it dont work.
Thanks for answers and ideas for advance!
I created a sample answer check the below code.
var myApp = angular.module('myApp', []);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
myApp.controller('MyCtrl', ['$scope', MyCtrl]);
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.names = [{
"name": "AAAAAA",
"down": "False"
}, {
"name": "BBBBBB",
"down": "45%"
}, {
"name": "CCCCC",
"down": "12%"
}, {
"name": "AAAAAA",
"down": "45%"
}];
$scope.datas = [{
"data": "AAAAAA/45%"
}, {
"data": "CCCCC/12%"
}];
$scope.getTheRightData = data => $scope.datas.map(param => {
return {
name: param.data.split('/')[0],
down: param.data.split('/')[1]
}
}).find(param => param.name == data.name && param.down == data.down);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myApp">
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<div ng-controller="MyCtrl">
<table>
<tbody>
<tr ng-repeat="name in names">
<td>{{name.name}}</td>
<td>{{name.down}}</td>
<td>{{getTheRightData(name)}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Please help me to find all selected radio button id for below code.
Here's an idea of what my HTML looks like
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<div>
<table cellpadding="2" cellspacing="2" border="1" ng-repeat="dep in DepList track by $index">
<tr>
<th> Name </th>
</tr>
<tr ng-repeat="item in ContactsList | findobj: dep.groupid">
<td>{{item.name}}</td>
<td><input type="radio" name="radius+{{$parent.$index}}" data-ng-value="{{item.id}}" ng-model="UniqueId" selected="true" /></td>
</tr>
</table>
</div>
<div>
<button ng-click="Select()">Select</button>
</div>
</div>
</div>
And here's my Controller
var myapp1 = angular.module('MyApp', []);
myapp1.controller('MyCtrl', function ($scope) {
$scope.DepList = [
{ dep: "computer", groupid: "1" },
{ dep: "english", groupid: "2" }
];
$scope.ContactsList = [
{
name: "Sijith",
id: "1",
groupid: "1"
},
{
name: "Deepak",
id: "1",
groupid: "2"
},
{
name: "Libi das",
id: "1",
groupid: "2"
},
{
name: "Noufal",
id: "1",
groupid: "1"
},
{
name: "Jijo",
id: "1",
groupid: "2"
}];
$scope.Select = function () {
alert($scope.UniqueId);
};
});
myapp1.filter('findobj', function () {
return function (ContactsList, id) {
return ContactsList.filter(function (l) {
if (l.groupid == id) {
return true;
}
});
};
});
There are few issue with the $scope.ContactsList binding with the radio button, you are binding the id of each element as the value of radio button , which should not be same if different radio button inside a group have different values.
I have done few changes in it to give each radio button a different value. I have also created a selectedContact list in which i will populated the selected radio buttons value with the group id the belong to.
var myapp1 = angular.module('MyApp', []);
myapp1.controller('MyCtrl', function($scope) {
$scope.DepList = [{
dep: "computer",
groupid: "1"
}, {
dep: "english",
groupid: "2"
}];
$scope.ContactsList = [{
name: "Sijith",
id: "1",
groupid: "1"
}, {
name: "Deepak",
id: "1",
groupid: "2"
}, {
name: "Libi das",
id: "2",
groupid: "2"
}, {
name: "Noufal",
id: "2",
groupid: "1"
}, {
name: "Jijo",
id: "3",
groupid: "2"
}];
$scope.selectedContact = [];
$scope.Select = function() {
alert("group id 1 selected contact id:"+ $scope.selectedContact.groupid1);
alert("group id 1 selected contact id:"+ $scope.selectedContact.groupid2);
};
});
myapp1.filter('findobj', function() {
return function(ContactsList, id) {
return ContactsList.filter(function(l) {
if (l.groupid == id) {
return true;
}
});
};
});
<script data-require="angular.js#1.4.x" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
<div ng-app="MyApp">
<div ng-controller="MyCtrl">
<div>
<table cellpadding="2" cellspacing="2" border="1" ng-repeat="dep in DepList track by $index">
<tr>
<th> Name </th>
</tr>
<tr ng-repeat="item in ContactsList | findobj: dep.groupid">
<td>{{item.name}}</td>
<td><input type="radio" name="radius+{{$parent.$index}}" data-ng-value="{{item.id}}" ng-model="selectedContact['groupid'+dep.groupid]" selected="true" /></td>
</tr>
</table>
</div>
<div>
<button ng-click="Select()">Select</button>
</div>
</div>
</div>
I am trying to implement the functionality of deleting multiple selected rows of table with single button click.
When I implement this functionality on a simple table created without directive it works fine: Working Plunker
But when I try to implement the same on the table created using reusable directive, it does not work: Non Working Plunker
Below is the code for my table with directive:
Index HTML:
<!DOCTYPE html>
<html ng-app="demoapp">
<head>
<title>My App</title>
<link rel="stylesheet" href="style.css">
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular-route.js"></script>
<script src="//cdn.jsdelivr.net/angular.bootstrap/0.11.0/ui-bootstrap-tpls.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<div ng-controller="TableCtrl" class="container">
<div class="row">
<div class="col-lg-12">
<div class="">
<div class="table-responsive">
<div class="ng-data-table" ng-dt="Demo"></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
_dataTable.html:
<table class="table table-bordered table-condensed table-hover">
<thead>
<tr>
<th ng-repeat="th in ngDt.Headers" class="text-center">
{{th.Name}}
<input ng-if="th.Type==='Selectable'" type="checkbox" ng-checked="ngDt.isSelectedAllRows()" ng-click="ngDt.selectAllRows($event)" class=""/>
<a ng-if="th.Type === 'Selectable' && ngDt.IsDeleteMultipleRowsIconVisible === true " class="text-danger delete-icon" ng-click="ngDt.deleteRow()">
<i class="fa fa-trash-o"></i>
</a>
</th>
</tr>
</thead>
<tbody>
<tr bindonce ng-repeat="row in ngDt.Rows" ng-class="ngDt.getRowClass(row);">
<td ng-repeat="cell in ngDt.Cells" class="text-center col-lg-6 col-md-6 col-sm-6 col-xs-6">
{{cell.Type === 'Normal' ? row[cell.Name] : ''}}
<input ng-if="cell.Type === 'Selectable'" type="checkbox" ng-checked="ngDt.isRowSelected(row)" ng-click="ngDt.selectRowChanged($event,row)" />
</td>
</tr>
</tbody>
</table>
JS:
// Code goes here
var appRoot = angular.module('demoapp', ['ngRoute', 'ui.bootstrap']);
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
//-------------------Directive-------------------//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
appRoot.directive('ngDataTable', function () {
return {
restrict: 'C',
replace: true,
scope: {
ngDt: "=ngDt"
},
templateUrl: "_dataTable.html"
};
});
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
//-------------------Directive-------------------//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
//--------------------Service--------------------//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
appRoot.service('MyService', function () {
return {
SelctedIds: [],
updateSelected: function (action, id) {
if (action === 'add' && this.SelctedIds.indexOf(id) === -1) {
this.SelctedIds.push(id);
}
if (action === 'remove' && this.SelctedIds.indexOf(id) !== -1) {
this.SelctedIds.splice(this.SelctedIds.indexOf(id), 1);
}
},
selectRowChanged: function ($event, id) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
this.updateSelected(action, id);
return this.SelctedIds;
},
selectAll: function ($event, obj, identifierKey) {
var tempAllIds = [];
angular.forEach(obj, function (value, key) {
tempAllIds.push(value[identifierKey]);
});
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
for (var i = 0; i < tempAllIds.length; i++) {
var id = tempAllIds[i];
this.updateSelected(action, id);
}
return this.SelctedIds;
},
isRowSelected: function (id) {
return this.SelctedIds.indexOf(id) >= 0;
},
getSelectedClass: function (id, selectionClassName) {
return this.isRowSelected(id) ? selectionClassName : '';
},
isSelectedAllRows: function (obj) {
if (obj !== undefined) {
return this.SelctedIds.length === obj.length;
} else {
return false;
}
}
};
});
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
//--------------------Service--------------------//
/*xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
appRoot.controller('TableCtrl', function ($scope, MyService) {
$scope.Demo = {};
$scope.Demo.Rows = [
{ "Id": "1", "Name": "Row1", "IsDeleted": false },
{ "Id": "2", "Name": "Row2", "IsDeleted": false },
{ "Id": "3", "Name": "Row3", "IsDeleted": false }
];
$scope.Demo.Headers = [
{ "Name": "Select", "Type": "Selectable" },
{ "Name": "Name", "Type": "Normal" }
];
$scope.Demo.Cells = [
{ "Name": "Select", "Type": "Selectable" },
{ "Name": "Name", "Type": "Normal" }
];
$scope.Demo.IsDeleteMultipleRowsIconVisible = false;
//----------------Multiple Delete----------------//
$scope.Demo.SelectedRows = [];
$scope.Demo.selectRowChanged = function ($event, row) {
var id = row.Id;
$scope.Demo.SelectedRows = MyService.selectRowChanged($event, id);
};
$scope.Demo.isRowSelected = function (row) {
var id = row.Id;
return MyService.isRowSelected(id);
};
$scope.Demo.selectAllRows = function ($event) {
$scope.Demo.SelectedRows = MyService.selectAll($event, $scope.Demo.Rows, "Id");
};
$scope.Demo.isSelectedAllRows = function () {
return MyService.isSelectedAllRows($scope.Demo.Rows);
};
$scope.Demo.getRowClass = function (row) {
var className = "";
if ($scope.Demo.SelectedRows.length > 0) {
className = MyService.getSelectedClass(row.Id, "bg-danger-muted");
}
if ($scope.Demo.SelectedRows.length > 0) {
$scope.Demo.IsDeleteMultipleRowsIconVisible = true;
} else {
$scope.Demo.IsDeleteMultipleRowsIconVisible = false;
}
return className;
};
$scope.Demo.deleteRow = function () {
for (var i = 0; i < $scope.Demo.SelectedRows.length; i++) {
for (var j = 0; j < $scope.Demo.Rows.length; j++) {
if ($scope.Demo.SelectedRows[i] === $scope.Demo.Rows[j].Id) {
$scope.Demo.Rows[j].IsDeleted = true;
}
}
}
};
//----------------Multiple Delete----------------//
});
What am I missing? Is there any better way to acomplish the same task to reduce the amount of code and make it more reusable?
You could use ng-repeat="row in ngDt.Rows| filter: {IsDeleted: false}" filter the Rows on basis of IsDeleted flag.
Markup
<tr bindonce ng-repeat="row in ngDt.Rows| filter: {IsDeleted: true}" ng-class="ngDt.getRowClass(row);">
<td ng-repeat="cell in ngDt.Cells" class="text-center col-lg-6 col-md-6 col-sm-6 col-xs-6">
{{cell.Type === 'Normal' ? row[cell.Name] : ''}}
<input ng-if="cell.Type === 'Selectable'" type="checkbox" ng-checked="ngDt.isRowSelected(row)" ng-click="ngDt.selectRowChanged($event,row)" />
</td>
</tr>
Plunkr Here
Answer for the second part of my question, may be helpful to someone:
Is there any better way to acomplish the same task to reduce the amount of code and make it more reusable?
I improved the delete functionality little to reduce the code.
Plunker
Index Html:
<div ng-controller="TableCtrl" class="container">
<div class="row">
<div class="col-lg-12">
<div class="">
<div class="table-responsive">
<div class="ng-data-table" ng-dt="Demo"></div>
</div>
</div>
</div>
</div>
</div>
_dataTable.html:
<table class="table table-bordered table-condensed table-hover">
<thead>
<tr>
<th ng-repeat="th in ngDt.Headers" class="text-center">
{{th.Name}}
<input ng-if="th.Type==='Selectable'" type="checkbox" ng-model="ngDt.IsAll" ng-click="ngDt.selectAllRows()" />
<a ng-if="th.Type === 'Selectable' && ngDt.isShowDeleteBtn() === true " class="text-danger delete-icon" ng-click="ngDt.removeSelectedRows()">
<i class="fa fa-trash-o"></i>
</a>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="row in ngDt.Rows" ng-class="{'warning' : row['IsSelected']}">
<td ng-repeat="cell in ngDt.Cells">
<input ng-if="cell.Type==='Selectable'" type="checkbox" ng-model="row['IsSelected']" ng-change="ngDt.isShowDeleteBtn()" />
{{(cell.Type==='Normal')?row[cell.Name]:''}}
</td>
</tr>
</tbody>
</table>
JS:
var appRoot = angular.module('demoapp', []);
//-------------------Directive-------------------//
appRoot.directive('ngDataTable', function () {
return {
restrict: 'C',
replace: true,
scope: {
ngDt: "=ngDt"
},
templateUrl: "_dataTable.html"
};
});
//-------------------Directive-------------------\\
//--------------------Service--------------------//
appRoot.service('MyService', function () {
return {
isShowDeleteBtn: function ($scope) {
var cnt = 0;
for (var i = 0; i < $scope[$scope.ObjName].Rows.length; i++) {
if ($scope[$scope.ObjName].Rows[i]['IsSelected'] === true) {
cnt++;
break;
}
}
return (cnt > 0);
},
selectAllRows: function ($scope) {
//check if all selected or not
if ($scope[$scope.ObjName].IsAll === false) {
//set all row selected
angular.forEach($scope[$scope.ObjName].Rows, function (row, index) {
$scope[$scope.ObjName].Rows[index]['IsSelected'] = true;
});
$scope[$scope.ObjName].IsAll = true;
} else {
//set all row unselected
angular.forEach($scope[$scope.ObjName].Rows, function (row, index) {
$scope[$scope.ObjName].Rows[index]['IsSelected'] = false;
});
$scope[$scope.ObjName].IsAll = false;
}
},
removeSelectedRows: function ($scope) {
//start from last index because starting from first index cause shifting
//in the array because of array.splice()
$scope[$scope.ObjName].SelectedIds = "";
for (var i = $scope[$scope.ObjName].Rows.length - 1; i >= 0; i--) {
if ($scope[$scope.ObjName].Rows[i].IsSelected) {
if ($scope[$scope.ObjName].SelectedIds === "") {
$scope[$scope.ObjName].SelectedIds += $scope[$scope.ObjName].Rows[i].Id;
} else {
$scope[$scope.ObjName].SelectedIds += "," + $scope[$scope.ObjName].Rows[i].Id;
}
//delete row from Rows
$scope[$scope.ObjName].Rows.splice(i, 1);
}
}
}
};
});
//--------------------Service--------------------\\
//------------------Controller-------------------//
appRoot.controller('TableCtrl', function ($scope, MyService) {
$scope.Demo = {};
$scope.ObjName = "Demo";
$scope.Demo.IsAll = false;
$scope.Demo.SelectedIds = "";
$scope.Demo.Rows = [{ "Id": "1", "Name": "Row1", "IsDeleted": false },{ "Id": "2", "Name": "Row2", "IsDeleted": false },{ "Id": "3", "Name": "Row3", "IsDeleted": false }];
$scope.Demo.Headers = [{ "Name": "Select", "Type": "Selectable" },{ "Name": "Name", "Type": "Normal" }];
$scope.Demo.Cells = [{ "Name": "Select", "Type": "Selectable" },{ "Name": "Name", "Type": "Normal" }];
$scope.Demo.isShowDeleteBtn = function () {
return MyService.isShowDeleteBtn($scope);
}
$scope.Demo.IsAll = false;
$scope.Demo.selectAllRows = function () {
MyService.selectAllRows($scope);
};
$scope.Demo.removeSelectedRows = function () {
MyService.removeSelectedRows($scope);
};
});
//------------------Controller-------------------\\