Add a class selectively to an ng-repeat AngularJS - angularjs

I have an ng-repeat for a table, I want to be able to add a class when <td> is clicked, and remove the class when un-clicked. Multiple <td> can be selected at the same time. Right now ALL of the cities are or are not getting the class applies.
For example: (lets say nodes has 100 items)
<tr ng-repeat node in nodes>
<td>{{node.name}}</td>
<td>{{node.date}}</td>
<td ng-click="toggleMe( node.city )" ng-class"{clicked : isClicked()}" >{{node.city}}</td>
</tr>
in my JS
$scope.cityArr = [];
$scope.toggleMe = function(city) {
if ($scope.count > 0) {
angular.forEach($scope.cityArr, function(value) {
if (city === value) {
$scope.clicked = false;
} else {
$scope.cityArr.push(city);
$scope.clicked = true;
}
});
} else {
$scope.cityArr.push(city);
$scope.clicked = true;
}
$scope.count = 1;
};
$scope.isClicked = function() {
return $scope.clicked;
};

Right now there is a single clicked property on the scope that you're changing and everything refers to that. Try to put clicked on the node instead...
$scope.toggleMe = function(node) {
if ($scope.count > 0) {
angular.forEach($scope.cityArr, function(value) {
if (node.city === value) {
node.clicked = false;
} else {
$scope.cityArr.push(node.city);
node.clicked = true;
}
});
} else {
$scope.cityArr.push(node.city);
node.clicked = true;
}
$scope.count = 1;
};
And in the ngRepeat...
<tr ng-repeat node in nodes>
<td>{{node.name}}</td>
<td>{{node.date}}</td>
<td ng-click="toggleMe( node )" ng-class"{clicked : node.clicked}" >{{node.city}}</td>
</tr>

You don't need a special function or controller to accomplish this:
<table>
<tbody>
<tr ng-repeat="node in nodes">
<td>{{node.name}}</td>
<td>{{node.date}}</td>
<td ng-click="node.highlight = !node.highlight"
ng-class="{ highlight: node.highlight }">
{{node.city}}
</td>
</tr>
</tbody>
</table>
Full Plunker example: http://plnkr.co/edit/1hdcIOfz0nHb91uFWKrv
I could show you the controller I used by it's empty except for the test data. You don't need a function.

Alternately, the code can use a separate array and $index to set classes:
<tr ng-repeat="node in nodes"
ng-class="{ highlight: highlightRows[$index] }">
<td class="x" ng-click="toggleHighlight($index)">
X
</td>
This approach is useful if you want to separate Model data from View data.
The DEMO
angular.module("app", [])
.controller("TestController", function($scope) {
$scope.highlightRows = [];
$scope.toggleHighlight = function(idx) {
$scope.highlightRows[idx] = !$scope.highlightRows[idx];
};
$scope.nodes = [
{ name: "Alpha", date: new Date(), city: "Omaha" },
{ name: "Bravo", date: new Date(), city: "New York" },
{ name: "Charlie", date: new Date(), city: "Minneapolis" }
];
})
table {
border-collapse: collapse;
font-family: sans-serif;
}
td {
padding: 5px;
border: solid black 1px;
}
.x {
cursor: pointer;
}
.highlight {
background: yellow;
}
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app" ng-controller="TestController">
<table>
<h3>Click on X to highlight</h3>
<tbody>
<tr ng-repeat="node in nodes"
ng-class="{ highlight: highlightRows[$index] }">
<td class="x" ng-click="toggleHighlight($index)">
X
</td>
<td>{{node.name}}</td>
<td>{{node.date | date}}</td>
<td>{{node.city}}</td>
</tr>
</tbody>
</table>
highlightRows={{highlightRows}}
</body>

Related

Angular filter table with search across two columns simultaneously

I have a table with multiple columns that I currently filter using a text input (search) field:
HTML (simplified):
<div class="search">
<input type="text" placeholder="Search" data-ng-model="vm.filter_on" />
</div>
<tr data-ng-repeat="product in vm.data | filter: vm.filter_on>
<td>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.brand}}</td>
</tr>
Let's say I have these three products:
{
id: 1,
name: "Waffles",
brand: "Walmart",
},
{
name: "Pizza",
brand: "Walmart",
},
{
name: "Soda",
brand: "Target",
}
If I enter "Walmart" in the search bar, I will see the first two objects. What I want to know is if it's possible to search "Walmart piz" and only be shown the second object--essentially, have the search term try to match across values from multiple columns.
Most of what I've found when looking for a solution has been about trying to set the specific columns a search will consider, but I haven't found anything that solves my exact use case.
I created a workaround using the nifty filter from this question, which solves the issue of searching with multiple fragments rather than full terms: AngularJS filter for multiple strings
But even then, I still need to combine the column data into a single string for the search to work. Is there any way to do this more elegantly in Angular?
You should create custom filter:
angular.module('app', []).controller('ctrl', function($scope) {
var vm = this;
vm.filter_on = "Walmart piz";
vm.data = [
{ id: 1, name: "Waffles", brand: "Walmart" },
{ name: "Pizza", brand: "Walmart" },
{ name: "Soda", brand: "Target" }
]
}).filter('custom', function(){
return function(input, search){
if(!search)
return input;
var items = search.split(' ').filter(x => x).map(x => x.toLowerCase());
return input.filter(x => {
for(var item of items){
var flag = false;
for(var prop in x){
if(prop != '$$hashKey' && (x[prop] + '').toLowerCase().indexOf(item) != -1){
flag = true;
break;
}
}
if(!flag)
return false;
}
return true;
})
}
})
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>
<div class="search" ng-app='app' ng-controller='ctrl as vm'>
<input type="text" placeholder="Search" ng-model="vm.filter_on" />
<br>
<br>
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>brand</th>
<tr>
</thead>
<tbody>
<tr data-ng-repeat="product in vm.data | custom: vm.filter_on">
<td>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.brand}}</td>
</tr>
</tbody>
</table>
</div>

ng-table: check box selection in each row

I have a ng-table where i am trying to implement selection using check box in each row.
<table id="List" class=" table table-bordered table-striped"
ng-table="tableParams" show-filter="true" template-pagination="custom/pager">
<tbody>
<tr ng-repeat="item in $data" >
<td style="width: 35px">
<input type="checkbox" name="selectedIds[]" value="{{item.id}}" ng-checked="isRowSelected(item.id)" ng-click="toggleSelection(item.id)" />
</td>
<td data-title="'Name'" sortable="'Name'" filter="{ 'Name': 'text' }" >
{{ item.Name}} </a>
</td>
<td data-title="'Email'" sortable="'Email'" >
{{ item.Email}}
</td>
<td data-title="'Phone Number'" sortable="'PhoneNumber'">
{{ item.PhoneNumber}}
</td>
</tr>
this is the controller:
angular.module("umbraco").controller("ListController",
function ($scope, $http, $routeParams) {
$scope.selectedIds = [];
$scope.toggleSelection = function (val) {
var idx = $scope.selectedIds.indexOf(val);
if (idx > -1) {
$scope.selectedIds.splice(idx, 1);
} else {
$scope.selectedIds.push(val);
}
};
$scope.isRowSelected = function (id) {
return $scope.selectedIds.indexOf(id) >= 0;
};
$scope.isAnythingSelected = function () {
return $scope.selectedIds.length > 0;
};
});
i am trying to select individual rows however the above code selecting all the rows on any row click.
any suggestion on this please?
You are not using the power of angular correctly :)
You should try something like that in your view:
<input type="checkbox" ng-checked="item.isRowSelected" ng-click="toggleSelection(item)" />
and in the controller:
$scope.toggleSelection = function(item){
item.isRowSelected = !item.isRowSelected;
}
$scope.isAnythingSelected = function () {
for(var i = 0; i < $scope.data.length; i++){
if($scope.data[i].isRowSelected === true){
return true;
}
}
return false;
};

AngularJs Sorting across all the pages

Can anybody help me with angularjs sorting across all the pages when I am using Server side pagination and sorting.
I am using ui-bootsrap for pagination;
Code as attached.
My sorting is happening only once in ascending order.Any idea how to sort in both direction ? i.e i m passing the sortBy as +property to sort i need to toggle the property with - infront once its sorted in asc order. Any directive to handle that toggle?
$scope.maxSize = 5;
$scope.currentPage = 1;
$scope.itemsPerPage = 5;
//This method gets called each time the page is loaded or move to next page
$scope.isResultExist = function (list) {
$scope.list = list;
return $scope.populateResult();
};
$scope.populateResult = function () {
if ($scope.list != undefined) {
$scope.totalItems = $scope.list.length;
var begin = (($scope.currentPage - 1) * $scope.itemsPerPage)
, end = begin + $scope.itemsPerPage;
$scope.result = $scope.list.slice(begin, end);
}
};
$scope.sort_by = function (sortBy) {
if ($scope.list != undefined) {
var sortOrder = 1;
$log.debug("**************list : " + $scope.list);
$scope.list.sort(function (a, b) {
for (var k = 0; k < $scope.list.length; k++) {
var valueA = a[sortBy];
var valueB = b[sortBy];
var result = (valueA < valueB) ? -1 : (valueA > valueB) ? 1 : 0;
return result * sortOrder;
}
});
$scope.populateResult();
}
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<th class="source"><a href="#" ng-click="sort_by('source')" data-toggle="tooltip" bs-tooltip
data-title="sort by Source ID">Source ID<i class="fa fa-sort"></i>
</a></th>
<tr data-ng-repeat="keyRingItem in result ">
Pagination:
<pagination items-per-page="itemsPerPage" total-items="totalItems" ng-model="currentPage"
max-size="maxSize" class="pagination-sm" boundary-links="true">
</pagination>
If your paging is being done server-side, then the sorting must be done server-side.
Angular will only be able to sort the page of data that it has.
Either implement the sorting server-side, or retrieve all data and implement the paging client-side.
$scope.propertyName = 'age';//Amol sorting angularjs
$scope.reverse = true;
$scope.Shiftsort = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
angular.module('orderByExample2', [])
.controller('ExampleController', ['$scope', function($scope) {
var friends = [
{name: 'John', phone: '555-1212', age: 10},
{name: 'Mary', phone: '555-9876', age: 19},
{name: 'Mike', phone: '555-4321', age: 21},
{name: 'Adam', phone: '555-5678', age: 35},
{name: 'Julie', phone: '555-8765', age: 29}
];
$scope.propertyName = 'age';
$scope.reverse = true;
$scope.friends = friends;
$scope.sortBy = function(propertyName) {
$scope.reverse = ($scope.propertyName === propertyName) ? !$scope.reverse : false;
$scope.propertyName = propertyName;
};
}]);
.friends {
border-collapse: collapse;
}
.friends th {
border-bottom: 1px solid;
}
.friends td, .friends th {
border-left: 1px solid;
padding: 5px 10px;
}
.friends td:first-child, .friends th:first-child {
border-left: none;
}
.sortorder:after {
content: '\25b2'; // BLACK UP-POINTING TRIANGLE
}
.sortorder.reverse:after {
content: '\25bc'; // BLACK DOWN-POINTING TRIANGLE
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.0/angular.min.js"></script>
<div ng-controller="ExampleController">
<pre>Sort by = {{propertyName}}; reverse = {{reverse}}</pre>
<hr/>
<button ng-click="propertyName = null; reverse = false">Set to unsorted</button>
<hr/>
<table class="friends">
<tr>
<th>
<button ng-click="sortBy('name')">Name</button>
<span class="sortorder" ng-show="propertyName === 'name'" ng-class="{reverse: reverse}"></span>
</th>
<th>
<button ng-click="sortBy('phone')">Phone Number</button>
<span class="sortorder" ng-show="propertyName === 'phone'" ng-class="{reverse: reverse}"></span>
</th>
<th>
<button ng-click="sortBy('age')">Age</button>
<span class="sortorder" ng-show="propertyName === 'age'" ng-class="{reverse: reverse}"></span>
</th>
</tr>
<tr ng-repeat="friend in friends | orderBy:propertyName:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>

Getting AngularJS orderBy to sort both directions

I'm attempting to setup a clickable table column header that sort Ascending when first clicked, and Descending when clicked again. My ascending sort is working fine, but I'm not sure how to setup an expression within my OrderBy to sort Descending
My setup thus far:
Table html has something like
<th ng-click="sort('LastName')">Last Name</th>
My sort method looks like
scope.sort = function (columnName) {
if (angular.isDefined(scope.filter)) {
if (scope.filter.SortColumn == columnName) {
scope.filter.SortColumn = columnName;
scope.filter.SortDirection = scope.filters.SortDirection == "Asc" ? "Desc" : "Asc";
} else {
scope.filter.SortColumn = columnName;
scope.filter.SortDirection = "Asc";
}
}
};
And my ng-repeat looks as follows
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn">
How can I get the SortDirection to factor into the orderBy?
To simply reverse you'd change it to this:
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn : true">
It'd be best if you used a boolean in your controller, but this should work too:
<tbody ng-repeat="name in resp.Names | orderBy : filter.SortColumn : filter.SortDirection === 'Desc'">
And just for fun, here's how I do sorting with filtering in my tables.
Controller:
$scope.search = { query: ''};
$scope.sort = { field: 'defaultField', descending: true};
$scope.order = function(newValue) {
if(newValue === $scope.sort.field) {
$scope.sort.descending = !$scope.sort.descending;
} else {
$scope.sort = {field: newValue, descending: false};
}
};
$scope.filteredDocuments = function() {
var a = $filter('filter')($scope.documents, {$:$scope.search.query});
var b = $filter('orderBy')(a, $scope.sort.field, $scope.sort.descending);
return b;
};
A search box for filtering:
<input type="text" ng-model="search.query">
A column header:
<th nowrap>
<a href ng-click="order('size')">Size </a>
<i ng-show="sort.field === 'size' && !sort.descending" class="fa fa-sort-amount-asc"></i>
<i ng-show="sort.field === 'size' && sort.descending" class="fa fa-sort-amount-desc"></i>
</th>
The row binding:
<tr ng-repeat="d in filteredDocuments()" >
A simplified version of the above answer:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>
<p>Click the table headers to change the sorting order:</p>
<div ng-app="myApp" ng-controller="namesCtrl">
<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')" >Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:mySortOrder">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>
</div>
<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
$scope.names = [
{name:'Jani',country:'Norway'},
{name:'Carl',country:'Sweden'},
{name:'Margareth',country:'England'},
{name:'Hege',country:'Norway'},
{name:'Joe',country:'Denmark'},
{name:'Gustav',country:'Sweden'},
{name:'Birgit',country:'Denmark'},
{name:'Mary',country:'England'},
{name:'Kai',country:'Norway'}
];
$scope.sorts={};
$scope.orderByMe = function(x) {
$scope.myOrderBy = x;
if(x in $scope.sorts) {
$scope.sorts[x]=!$scope.sorts[x];
} else {
$scope.sorts[x]=false;
}
$scope.mySortOrder=$scope.sorts[x];
}
});
</script>
</body>
</html>

how to reset a filter by leaving it empty?

I have a filter on a list :
<input ng-model="searchFileName" />
<table>
<tr ng-repeat="file in folders | filter:searchFileName">
<td><a ng-click="openFolder(file.name)">{{ file.name }}</a></td>
</tr>
</table>
I would like to clear searchFileName value when I click on a result.
This is openFolder function :
$scope.openFolder = function(name) {
$scope.searchFileName = null;
$http.jsonp($scope.server + '?open=' + encodeURIComponent($scope.buildTreePath()) + '&callback=JSON_CALLBACK').success(function(data){
$scope.folders = data;
});
}
}
I can't empty my filter field, it doesn't work... Where am I wrong ?
just use:
$scope.openFolder = function(name) {
$scope.searchFileName = null;
}
var app = angular.module('app', []);
app.controller('fCtrl', function($scope) {
$scope.folders = [
{
name: "Ala"
}, {
name: "Ata"
}, {
name: "Ara"
}, {
name: "Ama"
}
];
$scope.openFolder = function(name) {
$scope.searchFileName = null;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="fCtrl">
<input ng-model="searchFileName" />
<table>
<tr ng-repeat="file in folders | filter:searchFileName">
<td><a ng-click="openFolder(file.name)">{{ file.name }}</a>
</td>
</tr>
</table>
</div>
</div>

Resources