ngTable select all filtered data - angularjs

I'm trying to select only the rows from an ng-table with filtered data. Using the following code filters the table rows but even the rows that aren't shown are being selected:
controller:
let sampleData = [{id: 1, name: 'John Doe', gender: 'Male'},
{id: 2, name: 'Jane Doe', gender: 'Female'},
{id: 3, name: 'Mary Jane', gender: 'Female'},
{id: 4, name: 'Mary Poppins', gender: 'Female'}];
$scope.tableParams = new NgTableParams({
}, {
dataset: sampleData
});
$scope.checkboxes = {
checked: false,
items: {}
};
$scope.$watch(() => {
return $scope.checkboxes.checked;
}, (value) => {
sampleData.map((item) => {
$scope.checkboxes.items.id = value;
});
});
$scope.$watch(() => {
return $scope.checkboxes.items;
}, () => {
let checked = 0;
let unchecked = 0;
let total = sampleData.length;
sampleData.map((item) => {
if ($scope.checkboxes.items.id) {
checked++;
} else {
unchecked++;
}
});
if (unchecked === 0 || checked === 0) {
$scope.checkboxes.checked = checked === total;
}
angular.element($element[0].getElementsByClassName('select-all')).prop('indeterminate', (checked != 0 && unchecked != 0));
});
html:
<script type="text/ng-template" id="checkbox.html">
<input type="checkbox" ng-model="checkboxes.checked" class="select-all" value="">
</script>
<table class="table" ng-table="tableParams" show-filter="true">
<tr ng-repeat="item in $data track by $index">
<td header="'checkbox.html'">
<input type="checkbox" ng-model="checkboxes.items[item.id]">
</td>
<td data-title="'Name'" filter="{'name': 'text'}">
{{item.name}}
</td>
<td data-title="'Gender'" filter="{'gender': 'text'}">
{{item.gender}}
</td>
</tr>
</table>
When the table is filtered via name or gender, the table rerenders with the filtered data. When you click on the select all checkbox while the table is filtered, the filtered rows are selected. Unfortunately, when you clear the filter, the previously filtered out rows are also selected. The same is true when selecting all the filtered rows and then triggering an action that's supposed to get the selected items. (All ids are selected for the action.)
How can I only select the filtered rows? Thank you.

Okay, I got it to work. I just added a tableData object to the $scope so I can store the filtered data there. That's what I used for checking the selected items.
let sampleData = [{id: 1, name: 'John Doe', gender: 'Male'},
{id: 2, name: 'Jane Doe', gender: 'Female'},
{id: 3, name: 'Mary Jane', gender: 'Female'},
{id: 4, name: 'Mary Poppins', gender: 'Female'}];
$scope.tableData = {
filteredData: [],
checkboxes: {
checked: false,
items: {}
}
};
$scope.tableParams = new NgTableParams({
page: 1,
count: 10
}, {
total: data.length;
getData: ($defer, params) => {
let filter = params.filter();
let count = params.count();
let page = params.page();
let filteredData = filter ? $filter('filter')(data, filter) : data;
params.total(filteredData.length);
$scope.tableData.filteredData = filteredData;
$defer.resolve(filteredData.slice((page - 1) * count, page * count));
}
});
$scope.$watch(() => {
return $scope.tableData.checkboxes.checked;
}, (value) => {
$scope.tableData.filteredData.map((item) => {
$scope.tableData.checkboxes.items[item].id = value;
});
});
$scope.$watch(() => {
return $scope.tableData.checkboxes.items;
}, () => {
let checked = 0;
let unchecked = 0;
let data = $scope.tableData.filteredData;
let total = data.length;
let checkboxes = $scope.tableData.checkboxes;
data.map((item) => {
if (checkboxes.items[item].id) {
checked++;
} else {
unchecked++;
}
});
if (unchecked === 0 || checked === 0) {
checkboxes.checked = checked === total;
}
angular.element($element[0].getElementsByClassName('select-all')).prop('indeterminate', (checked != 0 && unchecked != 0));
});
Not really sure if this is the best way to go about it. Also, this doesn't change the select all checkbox's state to indeterminate when you filter > select all > clear filter.

in your second watch, change to return $scope.tableData.filteredData; may solve your problem

Related

Adding Selected Option Prices for Checkboxes - Using Svelte

I'm trying to get update the total as the checkboxes are selected and unselected (incase the user changes their mind and no longer wants the item). But I'm not sure how to get the actual value I have assigned to each toy. For example: If the user selects toy 1 and 3 they should see: You ordered Toy1, Toy3 and your total is $6.00. For now I assigned the values with the names themselves which isn't what I want but I just put that to show what I'm trying to do. Is their something else I should be using actually perform an operation to get the total?
<script>
let toylist = [];
let toynames = [
'Toy1 5.00',
'Toy2 5.00',
'Toy3 1.00',
];
function join(toylist) {
return toylist.join(', ');
}
</script>
{#each toynames as toy}
<label>
<input type=checkbox bind:group={toylist} value={toy}> {toy}
</label>
{/each}
{#if toylist.length === 0}
<p>Pick at least one toy</p>
{:else}
<p>
You ordered {toylist.join(', ')} and your total is
</p>
{/if}
Ok, first you should separate the toynames array into an array of names and values. Then you should bind to the checked property of the input.
In order to display the current state to the user, we need a reactive declaration. Let's call it total. It contains two functions. The first one gives back an array of the selected names, the second the sum of the selected values.
Both work by looking at the selected property of the object in the toylist array. This updates due to our binding of the checked attribute. I created a repl for you to toy ;-) around with
<script>
let toylist = [
{name: "Toy", value: 5, selected: false},
{name: "Elephant", value: 6, selected: false},
{name: "Choo-Choo", value: 1, selected: false}
]
$: total = {
names: toylist.reduce((acc, cV) => {
if (cV && cV.selected) {
return [...acc, cV.name];
} else return [...acc];
}, []),
values: toylist.reduce((acc, cV) => {
if (cV && cV.selected) {
return parseInt(acc) + parseInt(cV.value);
} else return parseInt(acc);
}, 0)
};
</script>
{#each toylist as {name,value, selected}}
<label>
<input type=checkbox bind:checked={selected} bind:value={value}> {name}
</label>
{/each}
{#if toylist.length === 0}
<p>Pick at least one toy</p>
{:else}
<p>
You ordered {total.names.length < 1 ? "nothing": total.names} and your total is {total.values}
</p>
{/if}
EDIT:
Here is the total function with a more classic syntax:
$: total = {
names: toylist.reduce(function(acc, cV) {
if (cV && cV.selected) {
return [...acc, cV.name];
} else return [...acc];
}, []),
values: toylist.reduce(function(acc, cV) {
if (cV && cV.selected) {
return parseInt(acc) + parseInt(cV.value);
} else return parseInt(acc);
}, 0)
};
And here without the ? operator:
<script>
function renderNames() {
if (total.names.length < 1) {
return "nothing";
} else {
return total.names;
}
}
</script>
<p>You ordered {renderNames()} and your total is {total.values}</p>
The best way to isolate the price of each toy would be to make your array of toys into an array of objects where 'name' is one key value pair and price another. For manipulating the data it would be helpful if each toy had an id, and I've added a 'selected' boolean value to each toy that is updated if they are added or removed from the "toylist". I've also added a 'total' variable to hold the total of selected toys prices.
I have played with your code a bit to make this work. I have used buttons instead of checkboxes but you could do it in any way you like. So give this code a go and it should be doing what you want.
<script>
let toylist = [];
let toys = [
{id: 1, name: 'Toy 1', price: 5.00, selected: false},
{id: 2, name: 'Toy 2', price: 5.00, selected: false},
{id: 3, name: 'Toy 3', price: 1.00, selected: false}
];
let total = 0.00
function join(toy) {
if(toy.selected === false) {
toylist = [...toylist, toy.name]
total = total+toy.price
let i = toys.findIndex(t => t.id === toy.id)
toys[i].selected = true
toys = toys
} else {
total = total-toy.price
let i = toys.findIndex(t => t.id === toy.id)
let i2 = toylist.findIndex(t => t === toy.name)
toylist.splice(i2, 1)
toylist = toylist
toys[i].selected = false
toys = toys
}
}
</script>
{#each toys as toy}
<label>
{toy.name}: ${toy.price} <button on:click="{() => join(toy)}" value={toy.name}>{toy.selected ? 'remove' : 'add'}</button>
</label>
{/each}
{#if toylist.length === 0}
<p>Pick at least one toy</p>
{:else}
<p>
You ordered {toylist} and your total is ${total}
</p>
{/if}

Vue.js filtering on array

I am trying to filter an array using a computed property in vue.js. I would like to search on on multiple fields, name, state, tags etc.
My data:
events: [
{
id: 1,
name: 'Name of event',
url: '#',
datetime: '2017-05-10T00:00:00Z',
description: 'The full text of the event',
state: 'VIC',
tags: [
'ordinary',
'advanced'
]
},
{
id: 2,
name: 'Another event',
url: '#',
datetime: '2017-05-12T00:00:00Z',
description: 'The full text of the event',
state: 'VIC',
tags: [
'beginner'
]
},
{
id: 3,
name: 'Great event',
url: '#',
datetime: '2017-05-18T00:00:00Z',
description: 'The full text of the event',
state: 'NSW',
tags: [
'beginner'
]
}
]
},
The following function works as expected, however I cant work out how to have it search the items in 'tags' (commented out).
searchevents: function(){
let result = this.events
if (this.filterValue){
result = result.filter(event =>
event.name.toLowerCase().includes(this.filterValue.toLowerCase()) ||
event.state.toLowerCase().includes(this.filterValue.toLowerCase())
// event.tags.toLowerCase().values().includes(this.filterValue.toLowerCase())
)
}
return result
}
The following returns a blank array, this method works ok when i have done it in angular but not in vue.
searchevents2: function(){
var searchRegex = new RegExp(this.filterValue,'i')
this.events.filter(function(event){
return !self.filterValue || searchRegex.test(event.name) || searchRegex.test(event.state)
})
}
Ideally I would either like to be able to list array items to filter by or just filter by the entire array.
Appreciate any help, first post here so be gentle. I have a lot more experience with Python than Javascript so i may also use incorrect terminology at times.
You weren't too far off.
For your searchEvents filter, you just needed to add the tag filter. Here's how you might do that.
searchevents: function(){
let result = this.events
if (!this.filterValue)
return result
const filterValue = this.filterValue.toLowerCase()
const filter = event =>
event.name.toLowerCase().includes(filterValue) ||
event.state.toLowerCase().includes(filterValue) ||
event.tags.some(tag => tag.toLowerCase().includes(filterValue))
return result.filter(filter)
}
Array.some() is a standard array method that returns true if any element of the array passes your test.
searchevents2: function(){
const searchRegex = new RegExp(this.filterValue,'i')
return this.events.filter(event =>
!this.filterValue || searchRegex.test(event.name) || searchRegex.test(event.state))
}
With searchEvents2 you really only left an errant self in there. Either you needed to set self before you executed the filter, or, as I have done here, turned it into an arrow function.
Example.
const app = new Vue ({
el: '#app',
data: {
search: '',
userList: [
{
id: 1,
name: "Prem"
},
{
id: 1,
name: "Chandu"
},
{
id: 1,
name: "Shravya"
}
]
},
computed: {
filteredAndSorted(){
// function to compare names
function compare(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
return this.userList.filter(user => {
return user.name.toLowerCase().includes(this.search.toLowerCase())
}).sort(compare)
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.js"></script>
<div id="app">
<div class="search-wrapper">
<input type="text" v-model="search" placeholder="Search title.."/>
<label>Search Users:</label>
</div>
<ul>
<li v-for="user in filteredAndSorted">{{user.name}}</li>
</ul>
</div>

React - populate dropdown from array inside object and filter data

everyone. I have a React App that is supposed to filter planetarium shows by different criteria. One of the criteria is supposed to have multiple values:
var shows = [
{ id: 1, name: 'Black Holes', showType: 'Full Dome', age: 'All Ages', grade: ['Late Elementary', 'High School'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_blackholes.png'},
{ id: 2, name: 'Astronaut', showType: 'Full Dome', age: 'All Ages', grade: ['Early Elementary,',' Late Elementary', 'High School'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_astronaut.png'},
{ id: 3, name: 'Laser Holidays', showType: 'Laser', age: '18+', grade: ['Late Elementary', 'High School', 'College'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_laserholidays.png'},
{ id: 4, name: 'The Gruffalo', showType: 'Flat Screen', age: 'All Ages', grade: ['Pre-K', 'Kinder'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_gruffalo.png'},
{ id: 5, name: 'Laser iPOP', showType: 'Laser', age: 'All Ages', grade: ['Late Elementary', 'High School', 'College'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_ipop.png'}
];
The "grade" property of the "shows" object can have multiple values, and I decided to put them in an array.
I need two things:
1 - I need to populate the "grade" dropdown with all the possible values, without repeated values;
2 - I need to be able filter shows according to what the user select in that dropdown, similar to what the "Show Type" and "Age" dropdowns. Any idea on how to do this? Thanks.
var shows = [
{ id: 1, name: 'Black Holes', showType: 'Full Dome', age: 'All Ages', grade: ['Late Elementary', 'High School'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_blackholes.png'},
{ id: 2, name: 'Astronaut', showType: 'Full Dome', age: 'All Ages', grade: ['Early Elementary,',' Late Elementary', 'High School'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_astronaut.png'},
{ id: 3, name: 'Laser Holidays', showType: 'Laser', age: '18+', grade: ['Late Elementary', 'High School', 'College'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_laserholidays.png'},
{ id: 4, name: 'The Gruffalo', showType: 'Flat Screen', age: 'All Ages', grade: ['Pre-K', 'Kinder'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_gruffalo.png'},
{ id: 5, name: 'Laser iPOP', showType: 'Laser', age: 'All Ages', grade: ['Late Elementary', 'High School', 'College'], cover:'http://www.starsatnight.org/sciencetheater/assets/File/200x300_ipop.png'}
];
// FilterForm React Class
var FilterForm = React.createClass({
getInitialState: function() {
return {
data: this.props.data,
showType: '',
age: '',
grade: '',
}
},
filterItems: function(val, type){
switch (type) {
case 'showType':
this.setState({showType: val});
break;
case 'age':
this.setState({age: val});
break;
case 'grade':
this.setState({grade: val});
break;
default:
break;
}
},
render: function() {
var filteredItems = this.props.data;
var state = this.state;
["showType", "age", "grade"].forEach(function(filterBy) {
var filterValue = state[filterBy];
if (filterValue){
filteredItems = filteredItems.filter(function(item){
return item[filterBy] === filterValue;
});
}
});
var showTypeArray = this.props.data.map(function(item) {return item.showType});
var ageArray = this.props.data.map(function(item) {return item.age});
// This array gets once instance of all grade options since one show can be good for several grades
var gradeArray = this.props.data.map(function(item){
return item.grade;
});
showTypeArray.unshift("");
ageArray.unshift("");
gradeArray.unshift("");
return(
<div className="container">
<FilterOptions
data={this.state.data}
showTypeOptions={showTypeArray}
ageOptions={ageArray}
gradeOptions={gradeArray}
changeOption={this.filterItems} />
<div className="filter-form">
<FilterItems data={filteredItems} />
</div>
</div>
)
}
});
// FilterOptions React Class
var FilterOptions = React.createClass({
changeOption: function(type, e) {
var val = e.target.value;
this.props.changeOption(val, type);
},
render: function(){
return (
<div className="filter-options">
<div className="filter-option">
<label>Show Type</label>
<select id="showType" value={this.props.showType} onChange={this.changeOption.bind(this, 'showType')}>
{this.props.showTypeOptions.map(function(option) {
return ( <option key={option} value={option}>{option}</option>)
})}
</select>
<label>Age</label>
<select id="age" value={this.props.age} onChange={this.changeOption.bind(this, 'age')}>
{this.props.ageOptions.map(function(option) {
return ( <option key={option} value={option}>{option}</option>)
})}
</select>
<label>Grade</label>
<select id="grade" value={this.props.grade} onChange={this.changeOption.bind(this, 'grade')}>
{this.props.gradeOptions.map(function(option) {
return ( <option key={option} value={option}>{option}</option>)
})}
</select>
</div>
</div>
);
}
});
// FilterItems React Class
var FilterItems = React.createClass({
render: function(){
return(
<div className="filter-items">
<br />
{this.props.data.map(function(item){
return(
<div className="filter-item">{item.id} - {item.name} - {item.showType} - {item.age}</div>
);
})}
</div>
)
}
});
ReactDOM.render(
<FilterForm data={shows}/>,
document.getElementById('show-catalog')
);
<script src="https://unpkg.com/react#15/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15/dist/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<div id="show-catalog"></div>
1) You can get a set of unique values from an array using Set. For example,
var gradeArray = this.props.data.map(function(item){
return item.grade;
});
var uniqueGrades = Array.from(new Set(gradeArray));
2) What is not working about your current code?

How to get and compare values in table from another table in angularjs?

I am new at angularjs. So, it might be fool question.Anyway, please let me explain my problem. I have a table which is listed by ng-repeat and I'd like to change a column datas with another datas in another table column.
<tr data-ng-repeat=" list in listTypes">
<td>{{list.Comments}}</td>
<td>{{list.Modul}}</td>
<td>{{list.UserId}}</td>
<td data-ng-repeat="user in userNames">{{user.UserName}}</td>
I want to get UserName instead of UserId, but the problem that UserName is recorded in another table. Here is my angular for getting listTypes :
$scope.GetList = function () {
var onSuccess = function (response, status) {
//1
$scope.listTypes = response.Data;
var str = response.Data;
$scope.listTypes = eval('(' + str + ')');
for (var key in $scope.listTypes) {
$scope.listTypes[key].selected = "";
}
$scope.GetUserNames();
};
var data = null;
var request = $rest.GetList(data);
NGTools.CallNgServiceWithRequest(request, onSuccess, "GetList");
};
And trying to get usernames with this code:
$scope.userdatas= [];
$scope.userNames = [];
$scope.GetUserNames = function () {
var onSuccess = function (response, status) {
//1
$scope.userNames = response.Data;
};
$scope.userdatas= $scope.listTypes.UserId;
var data = { userdatas: JSON.stringify( $scope.userdatas) };
var request = $rest.GetUserNames(data);
NGTools.CallNgServiceWithRequest(request, onSuccess, "GetUserNames");
};
but it doesn't work. I couldn't figure out what's wrong with this code block. Please let me know if any tip is available. Thank you!
Assuming that you have to collections in your scope - one of which holds the id of the user, and the other holding the name, like so:
$scope.users = [
{ id: 1, name: 'John Doe' },
{ id: 2, name: 'Jane Doe' },
{ id: 3, name: 'Janice Doe' } ];
$scope.userInfo = [
{ userId: 1, gender: 'male' },
{ userId: 2, gender: 'female' },
{ userId: 3, gender: 'female' }];
Then what you could do is ng-repeat over the one with the userInfo and in your binding expression - use the id to get the name from the other collection:
<li ng-repeat="item in userInfo">
{{ item.gender }} {{ getNameFor(item.userId) }}</li>
Where the getNameFor is defined as:
$scope.getNameFor = function(id) {
var user = $scope.users.filter(function(item) { return item.id === id })[0];
console.log(user);
return user.name;
Which I checked in a fiddle here: http://jsfiddle.net/01kmoxw9/

angularJs filter nested object Track by

I created a custom filter, but its giving me an error
I created a fiddle here:
Fiddle
I have this user data:
data: [{
profile: {
firstName: 'John',
lastName: 'OConner'
}
}, {
profile: {
firstName: 'Smith',
lastName: 'OConner'
}
}, {
profile: {
firstName: 'James',
lastName: 'Bond'
}
}]
And I need to filter by the nested obj - profile by this
data: [{
column: {
label: 'firstName',
}
}, {
column: {
label: 'lastName',
}
}]
I can filter but is giving me this error:
this is my filter:
myApp.filter('testFilter', ['$filter',
function($filter) {
return function(items, selectedFilter) {
var returnArray = items;
var filtered = [];
var process = {};
process.filtered = [];
process.loop = function(obj, key) {
var filtered = [];
this.obj = obj;
this.key = key;
// console.log('obj--> ', obj);
// console.log('key--> ', key);
filtered = filtered.concat($filter('filter')(items, process.superFilter));
if (filtered.length > 0) {
process.filtered = filtered;
}
};
process.superFilter = function(value) {
var returnMe;
var originalValue = value.profile[process.key];
if (typeof(value) === 'String') {
originalValue = originalValue.toLowerCase();
}
if (originalValue === process.obj) {
console.log('found');
returnMe = value;
return returnMe;
}
};
if (Object.getOwnPropertyNames(selectedFilter).length !== 0) {
angular.forEach(selectedFilter, function(obj) {
filtered = filtered.concat($filter('filter')(items, obj));
});
returnArray = filtered;
// console.log('selectedFilter ', selectedFilter);
}
return returnArray;
};
}
]);
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. How can I solve this issue?
You need to use track by as the error suggests. If you don't have a unique key to use you can use $index.
ng-repeat='talent in talents.data | testFilter:filterInput track by $index'
Here is a working example with your code: http://jsfiddle.net/hwT4P/

Resources