Automatically set checkbox to true based on an integer - angularjs

Hi I need to convert or use the sent integer value from the checkboxes at the reserve page to the view/print transaction page.
Please see my old question:
How to add IDs of a checkbox in angular js
I am able to get the values from the database and display it on the view page the only problem is that the checkboxes are null. There are 5 checkboxes on the reservation page (Laptop, Headset, Projector, Tablet, Speakers) so the possible combinations are 32 that's why i used to send an integer from 0 - 31 to the database because there's only one column for the reserved items.
I have successfully manage (with the help of this community) to post and get values from the database.
Now please help me to convert/use that INT value to automatically set the checkbox value to true if it was checked by the user on the reserve page.
Example:
Laptop = 1; Headset = 2; Projector = 4; Tablet = 8; Speakers = 16
The user checks (reserve page)
✓ Laptop, Headset, ✓ Projector, Tablet, ✓ Speakers
The value on the DB: 21
One the view/print page
I need to use the int value on the DB (which is 21) to automatically check the checkbox ✓ Laptop, Headset, ✓ Projector, Tablet, ✓ Speakers in read-only disabled mode .
So far this is my code in html and controller:
function getReservedRequestsById(reservedRequestId) {
var key = reservedRequestId;
return dataservice.getReservedRequests(key).then(function (data) {
vm.ReservedRequestId = data.data;
console.log(vm.ReservedRequestId);
logger.info('ACTIVATED');
//CheckBox
if (vm.ReservedRequestId.Items > 15) {
$scope.chkItems.forEach(function (Item) {
if (Item.id == 16) {
Item.value = true;
}
})
}
else if ((16 > vm.ReservedRequestId.Items > 7) || (32 > vm.ReservedRequestId.Items > 23)) {
$scope.chkItems.forEach(function (Item) {
if (Item.id == 8) {
Item.value = true;
}
})
}
else if ((8 > vm.ReservedRequestId.Items > 3) || (16 > vm.ReservedRequestId.Items > 11) || (24 > vm.ReservedRequestId.Items > 19) || (32 > vm.ReservedRequestId.Items > 27)) {
$scope.chkItems.forEach(function (Item) {
if (Item.id == 4) {
Item.value = true;
}
})
}
// AND also for 1 & 2 i did not put it here because i would like to just test if it is working on the three check boxes. If it is working i'll just add the other two
}
<md-input-container class="md-block" flex-gt-sm>
<label class="force-input-label">Items</label>
</br>
<div ng-repeat="chkItem in chkItems">
<md-checkbox name="chkItem.name" ng-model="chkItem.value" readonly>{{chkItem.name}}
</div>
</md-input-container>
it is not currently working
Need help and advice
Not good in english as well as in angularjs/web development : )
your help is greatly appreciated!

I fixed your code. I only kept the logic you provided. The problem was that 16 > x > 7 is not a correct syntax in javascript. You have to use &&.
//Laptop = 1; Headset = 2; Projector = 4; Tablet = 8; Speakers = 16
var chkItems = [{
id: 1,
name: 'Laptop',
value: null,
}, {
id: 2,
name: 'Headset',
value: null
}, {
id: 4,
name: 'Projector',
value: null
}, {
id: 8,
name: 'Tablet',
value: null
}, {
id: 16,
name: 'Speakers',
value: null
}];
var items = 21;
if (items >= 16) {
selectItem(16);
}
if ((items < 16 && items > 7) || (items < 32 && items > 23)) {
selectItem(8);
}
if ((items < 8 && items > 3) || (items < 16 && items > 11) || (items < 24 && items > 19) || (items < 32 && items > 27)) {
selectItem(4);
}
console.log(chkItems);
function selectItem(id) {
chkItems.map(function(elem) {
if (!elem.value)
elem.value = (elem.id === id);
return elem;
});
}

Related

angularJS -UI-grid cellTooltip for dynamic columns

I have a stored procedure that returns dynamic columns and I was able to paint the output with some help on angularJS ui-grid. Now I am trying to add "CellToolTip". Screenshot below is the output of the stored procedure in which columns 25 to 22 are dynamic (which means they can range from 150 to 0 depending on the input given to the stored procedure). The columns that start with "Tgt"are Targets which I don't want to display but show the target value when hovered over the column. I was able to successfully hide the "Tgt-"columns on the webpage with out issue.
Now I need to show them as a CellToolTip when I hover over the dynamic columns 25 to 22 with which I need help. In the screenshot example below when I hover over the cell with value 0.901 that is against column 25 and row "Vat Fill Calc F/P Ratio" attributename I would like to see "0.89". But if I hover over the cell value 0.89 that is against column 25 and row "Vat Batch data F/P" attributename I would like to see "No value" since Tgt-25 column has a NULL for that attributeName.
In my code below within the push function I added "var key = 'Tgt-' + sortedKeysArray[i];
var value = row.entity[key];". When I put break points I get error saying key is undefined. But if I hardcode the key value like "var value = row.entity["Tgt-25"];" then it works fine. I need help with making the hover values dynamic in which I would like to get the target values from their respective target columns. Thanks in advance for the help.
LRWService.getVatMakeRpt('1', '1221209', '100000028', '2020-05-08', '2020-05-08').success(function (data) {
if (data === null || data.VatMakeRptList === null || data.VatMakeRptList.length === 0) {
$scope.error = true;
$scope.errorDescription = "No data found for selected criteria.";
} else {
$scope.gridOptionsVatMakeRpt.paginationPageSizes.push(
data.VatMakeRptList.length
);
var VatMakeRptList = data.VatMakeRptList;
var keysArray = [];
keysArray = Object.keys(VatMakeRptList[0]);
var sortedKeysArray = keysArray.sort().reverse();
$scope.gridOptionsVatMakeRpt.columnDefs.push({ name: 'LineNumber', field: 'LineNumber', width: '20%', visible: true });
$scope.gridOptionsVatMakeRpt.columnDefs.push({ name: 'AttributeName', field: 'AttributeName', width: '20%', visible: true });
for (var i = 0; i < sortedKeysArray.length; i++) {
if (!(sortedKeysArray[i] == "LineNumber" || sortedKeysArray[i] == "AttributeName" || sortedKeysArray[i].includes("Tgt-") == true ))
$scope.gridOptionsVatMakeRpt.columnDefs.push({
name: sortedKeysArray[i], field: sortedKeysArray[i], width: '20%', visible: true, cellTooltip: function (row, col) {
var key = 'Tgt-' + sortedKeysArray[i];
// var value = row.entity["Tgt-25"];
var value = row.entity[key];
if (value != null) {
return value;
} else {
return "No Value";
}
}
});
}
}
All I had to do was move the "Key" value above the if statement.
for (var i = 0; i < sortedKeysArray.length; i++) {
var key = 'Tgt-' + sortedKeysArray[i];
if (!(sortedKeysArray[i] == "LineNumber" || sortedKeysArray[i] == "AttributeName" || sortedKeysArray[i].includes("Tgt-") == true ))
$scope.gridOptionsVatMakeRpt.columnDefs.push({
name: sortedKeysArray[i], field: sortedKeysArray[i], width: '20%', visible: true, cellTooltip: function (row, col) {
// var value = row.entity["Tgt-25"];
var value = row.entity[key];
if (value != null) {
return value;
} else {
return "No Value";
}
}

How to put filtering feature in an array of objects

I have an ionic mobile application there's a filter search button but I am having a hard time how to filter array of objects.
Assuming I have an array of objects structured like this
initializeItems() {
this.items = [
{Place:"Dumaguete city", date:"February 2 2018"},
{Place:"Sibulan", date:"February 2 2018"},
{Place:"Bacong", date:"February 3 2018"},
{Place:"Manila", date:"February 4 2018"},
{Place:"Netherlands", date:"February 4 2018"},
{Place:"India", date:"February 5 2018"},
{Place:"USA", date:"February 7 2018"}
];
Filter codes below:
getItems(ev: any) {
console.log(this.items);
// Reset items back to all of the items
this.initializeItems();
// set val to the value of the searchbar
let val = ev.target.value;
// if the value is an empty string don't filter the items
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
}
How do I put filter feature in a array of objects?
You need to search in your objects values, not the array item
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.Place.toLowerCase().indexOf(val.toLowerCase()) > -1 ||
item.date.toLowerCase().indexOf(val.toLowerCase()));
})
}
You need to pass in the property/properties you want check against, currently you are just testing the object in the array which will check against the object itself not the properties within.
var items = [
{Place:"Dumaguete city", date:"February 2 2018"},
{Place:"Sibulan", date:"February 2 2018"},
{Place:"Bacong", date:"February 3 2018"},
{Place:"Manila", date:"February 4 2018"},
{Place:"Netherlands", date:"February 4 2018"},
{Place:"India", date:"February 5 2018"},
{Place:"USA", date:"February 7 2018"}
];
var val = 'Manila';
if (val && val.trim() != '') {
items = items.filter((item) => {
if( item.Place.toLowerCase().indexOf(val.toLowerCase()) > -1 ){
var node = document.createElement("LI");
var textnode = document.createTextNode(item.Place);
node.appendChild(textnode);
document.getElementById('filter').appendChild(node);
}
})
}
The items has several objects and every object has to two members (Place and date). In the filter you must specify what member should be filtered. In the below code I have choosen Place.
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.Palce.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
You could choose another one or both.
Update
If you want your filter works for both member, just add new condition with or operator.
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.Place.toLowerCase().indexOf(val.toLowerCase()) > -1 || item.date.toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
As you have mentioned in the comment, you want to have the date member of your objects as timestamp and you want to have an ability to filter it too.
Well, Javascript Date object has several constructors, one of them takes timestamp. So, we can use it to solve the problem.
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
return (item.Place.toLowerCase().indexOf(val.toLowerCase()) > -1 || (new Date(Number(item.date))).toString().toLowerCase().indexOf(val.toLowerCase()) > -1);
})
}
or
if (val && val.trim() != '') {
this.items = this.items.filter((item) => {
const placeResult = item.Place.toLowerCase().indexOf(val.toLowerCase()) > -1;
const theDate = new Date(Number(item.date));
const dateResult = theDate.toString().toLowerCase().indexOf(val.toLowerCase()) > -1;
return placeResult || dateResult;
})
}

How to sort / order array in Ionic 2? [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
Closed 5 years ago.
I have a page with one list from a JSON file. I want to add a sort button functionality. Below is my code of .ts , .html and picture of console.log of the array.
home.ts code:
this._servall.myservice(this.taskdesc).subscribe(data => {
console.log(data);
this.displaylist = data;
home.html code:
<ion-list no-lines *ngFor="let list of displaylist;let i=index;" >
<ion-item>
<p>{{list.TASKDESC}}</p>
<p>{{list.PRIMARY}}</p>
<p>{{list.DEADLINE_DT}}</p>
</ion-item>
</ion-list>
I want to sort the list with list.PRIMARY //this is a name
I want to sort the list with list.DEADLINE_DT // in increasing order, this is date
Below is the console.log image of this.displaylist array
Create one pipe for sorting
orderbypipe.ts
/*
* Example use
* Basic Array of single type: *ngFor="#todo of todoService.todos | orderBy : '-'"
* Multidimensional Array Sort on single column: *ngFor="#todo of todoService.todos | orderBy : ['-status']"
* Multidimensional Array Sort on multiple columns: *ngFor="#todo of todoService.todos | orderBy : ['status', '-title']"
*/
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({ name: 'order', pure: false })
export class OrderBy implements PipeTransform {
static _orderByComparator(a: any, b: any): number {
if ((isNaN(parseFloat(a)) || !isFinite(a)) || (isNaN(parseFloat(b)) || !isFinite(b))) {
//Isn't a number so lowercase the string to properly compare
if (a.toLowerCase() < b.toLowerCase()) return -1;
if (a.toLowerCase() > b.toLowerCase()) return 1;
}
else {
//Parse strings as numbers to compare properly
if (parseFloat(a) < parseFloat(b)) return -1;
if (parseFloat(a) > parseFloat(b)) return 1;
}
return 0; //equal each other
}
transform(input: any, [config = '+']): any {
if (!Array.isArray(input)) return input;
if (!Array.isArray(config) || (Array.isArray(config) && config.length == 1)) {
var propertyToCheck: string = !Array.isArray(config) ? config : config[0];
var desc = propertyToCheck.substr(0, 1) == '-';
//Basic array
if (!propertyToCheck || propertyToCheck == '-' || propertyToCheck == '+') {
return !desc ? input.sort() : input.sort().reverse();
}
else {
var property: string = propertyToCheck.substr(0, 1) == '+' || propertyToCheck.substr(0, 1) == '-'
? propertyToCheck.substr(1)
: propertyToCheck;
return input.sort(function(a: any, b: any) {
return !desc
? OrderBy._orderByComparator(a[property], b[property])
: -OrderBy._orderByComparator(a[property], b[property]);
});
}
}
else {
//Loop over property of the array in order and sort
return input.sort(function(a: any, b: any) {
for (var i: number = 0; i < config.length; i++) {
var desc = config[i].substr(0, 1) == '-';
var property = config[i].substr(0, 1) == '+' || config[i].substr(0, 1) == '-'
? config[i].substr(1)
: config[i];
var comparison = !desc
? OrderBy._orderByComparator(a[property], b[property])
: -OrderBy._orderByComparator(a[property], b[property]);
//Don't return 0 yet in case of needing to sort by next property
if (comparison != 0) return comparison;
}
return 0; //equal each other
});
}
}
}
Html
<ion-list no-lines *ngFor="let list of displaylist | order : ['+PRIMARY'];let i=index;" >
For more details see this http://www.fueltravel.com/blog/migrating-from-angular-1-to-2-part-1-pipes/

filtering in angularjs using or operator

i have a loop of an array Countries,example (this is in a multi select box)
{Clicked : true, Name:USA,ID:1},
{Clicked :false, Name:China,ID:2},
{Clicked : true, Name:India,ID:4}
when an item(Name value) is checked,the clicked value turns to true.So if i know all the values that are true can i loop through the countries array to get those values?
once i got the true values i want to use the OR operator to pass only one id value and not all, example if its 1 || 4 || 2 then 4 should get passed.
what was attempted
$scope.FilterCountries=function(){
var Clicked=true;
for(var i=0;i<=$scope.model.Countries.length;i++)
{
Clicked= $scope.model.Countries.Clicked[i];
var ID= Clicked || $scope.model.Countries.ID[i];
}
}
the above when i select a value,it sends back a different ID ,it adds its own value.
I am still not sure what you want to do exactly but your code seems to be wrong. I put an example together.
If you mean Bitwise operations see here: MDN Bitwise operations
I hope it helps.
$scope = {
model: {
Countries: [{
Clicked: true,
ID: 1
}, {
Clicked: true,
ID: 2
}, {
Clicked: true,
ID: 4
}]
}
};
$scope.FilterCountries = function() {
var result = 0;
for (var i = 0; i < $scope.model.Countries.length; i++) {
if ($scope.model.Countries[i].Clicked === true) {
//Bitwise operation ID: 1 and 2 and 4 would result in 7
result = result | $scope.model.Countries[i].ID;
}
}
return result;
};
document.write($scope.FilterCountries());
Later you can test if a country was checked by using the &-Operator
(7 & 4) === 4; // true
$scope.FilterCountries = function() {
var result = 0;
for (var i = 0; i < $scope.model.Countries.length; i++) {
if ($scope.model.Countries[i].Clicked === true) {
//Bitwise operation ID: 1 and 2 and 4 would result in 7
result = result[i] | $scope.model.Countries[i].ID;
}
}
return result;
};

AngularJS - ngRepeat & ngShow & Custom Filter - Optimization

I wrote a simple filter that gets a localized text. I use it in a list. When a word is not found I want to hide the item. I manage to solve the problem like this:
<ion-item ng-repeat="(key, data) in details" ng-if="key != 'Id' && key != 'Invoices' && key != 'Number' && key != 'Attributes' && data && key!= null" ng-show="(key | translate: clientCode:'Payments':'es').length > 0">
<p style="float:left; text-transform: capitalize;">{{key | translate: clientCode:'Payments':'es'}}:</p>
<p style="float:right;">{{data}}</p>
</ion-item>
However I am using the filter twice in each item which makes me feel weird. Is there a better way to do this? Thanks you all very much.
If it helps here is my filter code:
.filter("translate", function(Text) {
var data = null, serviceInvoked = false;
function realFilter(input) {
for(var i = 0; i < data.length; i++)
{
if(data[i].Field == input)
{
//console.log(data[i].Description);
return data[i].Description;
}
}
}
testFilter.$stateful = true;
function testFilter(input, clientCode, type, lang) {
if( data === null ) {
if( !serviceInvoked ) {
serviceInvoked = true;
var texts = Text.query({"clientCode": clientCode, "type": type, "lang": lang});
texts.$promise.then(function() {
data = texts;
});
}
return "-";
}
else return realFilter(input);
}
return testFilter;
});

Resources