how to add an array to localstore in angularjs - javascript

I am trying to build a shopping cart. I want to add the array invoice to localstorage so that i could access it later.
I guess there are some errors with this form of approach
angular.module('myApp', ['ngCookies']);
function CartForm($scope, $cookieStore) {
$scope.invoice.items = $cookieStore.get('items');
$scope.addItem = function() {
$scope.invoice.items.push({
qty: 1,
description: '',
cost: 0
});
$scope.invoice.items = $cookieStore.put('items');
},
$scope.removeItem = function(index) {
$scope.invoice.items.splice(index, 1);
$scope.invoice.items = $cookieStore.put('items');
},
$scope.total = function() {
var total = 0;
angular.forEach($scope.invoice.items, function(item) {
total += item.qty * item.cost;
})
return total;
}
}
HTML contains a button , which pushes the new items to the array which gets automatically binded.
<div ng:controller="CartForm">
<table class="table">
<tr>
<th>Description</th>
<th>Qty</th>
<th>Cost</th>
<th>Total</th>
<th></th>
</tr>
<tr ng:repeat="item in invoice.items">
<td><input type="text" ng:model="item.description"class="input-small"></td>
<td><input type="number" ng:model="item.qty" ng:required class="input-mini"> </td>
<td><input type="number" ng:model="item.cost" ng:required class="input-mini"> </td>
<td>{{item.qty * item.cost | currency}}</td>
<td>
[<a href ng:click="removeItem($index)">X</a>]
</td>
</tr>
<tr>
<td><a href ng:click="addItem()" class="btn btn-small">add item</a></td>
<td></td>
<td>Total:</td>
<td>{{total() | currency}}</td>
</tr>
</table>
</div>

Local stage saves only strings, not complex objects.
What you can do, therefore, is stringify it when saving and re-parse it when accessing it.
localStorage['foo'] = JSON.stringify([1, 2, 3]);
Be aware that the stringify process will strip out any unsuitable elements in the array, e.g. functions.
To re-parse it:
var arr = JSON.parse(localStorage['foo']);

localStorage["items"] = JSON.stringify(items);
update: you can retrieve it as follows: `var items:
localStorage.getItem('items');
source

localStorage supports only strings, so that why you must use JSON.stringify() and JSON.parse() to work via localStorage.
var p = [];
p[0] = "some";
localStorage["p"] = JSON.stringify(p);
For your code:
var items = [{
qty: 10,
description: 'item',
cost: 9.95}];
localStorage.setItem("items", JSON.stringify(items));
// get
var items = JSON.parse(localStorage.getItem("items"));

localStorage supports only strings, so you must use the following code:
var p = [];
p[0] = "some";
localStorage["p"] = JSON.stringify(p);

Related

How to concatenate strings from separate elements with jquery / javascript

I am wanting to concatenate strings from 2 separate elements and have them stored in a variable.
Currently my code is setting the variable equal to:
"Daily: 1070300, Weekly: 1070300, Monthly: 1070300"
My goal is to make the variable in the console equal to:
"Daily: 10, Weekly: 70, Monthly: 300"
$(document).ready(function() {
var str = '';
$('tbody > tr').each(function() {
$(this).find('.key').each(function() {
str += $(this).text() + ": " + $(this).parents().siblings('tr').find('.value').text() + ", ";
})
});
console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th class="key">Daily</th>
<th class="key">Weekly</th>
<th class="key">Monthly</th>
</tr>
<tr>
<td class="value">10</td>
<td class="value">70</td>
<td class="value">300</td>
</tr>
</tbody>
</table>
Thank you for your help all!
Each time through the key loop, you're grabbing the content of all three value cells (since $(this).parents().siblings('tr').find('.value') matches all three). There are many ways to fix this but one easy one I see is to use the index argument on the inner loop to select the value cell corresponding to the current key (using jQuery's eq function):
$(document).ready(function() {
var str = '';
$('tbody > tr').each(function() {
$(this).find('.key').each(function(index) {
str += $(this).text() + ": " + $(this).parents().siblings('tr').find('.value').eq(index).text() + ", ";
})
});
console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th class="key">Daily</th>
<th class="key">Weekly</th>
<th class="key">Monthly</th>
</tr>
<tr>
<td class="value">10</td>
<td class="value">70</td>
<td class="value">300</td>
</tr>
</tbody>
</table>
The code is very inefficient when you keep looking up stuff in the loop. So fixing it to read the index would work, it just causes the code to do more work than needed.
How can it be improved. Look up the two rows and one loop using the indexes.
var keys = $("table .key") //select the keys
var values = $("table .value") //select the values
var items = [] // place to store the pairs
keys.each(function(index, elem){ //loop over the keys
items.push(elem.textContent + " : " + values[index].textContent) // read the text and use the index to get the value
})
console.log(items.join(", ")) // build your final string by joing the array together
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th class="key">Daily</th>
<th class="key">Weekly</th>
<th class="key">Monthly</th>
</tr>
<tr>
<td class="value">10</td>
<td class="value">70</td>
<td class="value">300</td>
</tr>
</tbody>
</table>
Collect the .key and .value classes into a NodeList convert the NodeList into arrays. Then merge the 2 arrays into key/value pairs stored in an Object Literal. Finally convert the object into a string so it can be displayed.
Demo
Details are commented in Demo
// Collect all th.key into a NodeList and turn it into an array
var keys = Array.from(document.querySelectorAll('.key'));
// As above with all td.value
var vals = Array.from(document.querySelectorAll('.value'));
function kvMerge(arr1, arr2) {
// Declare empty arrays and an object literal
var K = [];
var V = [];
var entries = {};
/* map the first array...
|| Extract text out of the arrays
|| Push text into a new array
|| Then assign each of the key/value pairs to the object
*/
arr1.map(function(n1, idx) {
var txt1 = n1.textContent;
var txt2 = arr2[idx].textContent;
K.push(txt1);
V.push(txt2);
entries[K[idx]] = V[idx];
});
return entries;
}
var result = kvMerge(keys, vals);
console.log(result);
// Reference the display area
var view = document.querySelector('.display');
// Change entries object into a string
var text = JSON.stringify(result);
// Clean up the text
var final = text.replace(/[{"}]{1,}/g, ``);
// Display the text
view.textContent = final
<table>
<tbody>
<tr>
<th class="key">Daily</th>
<th class="key">Weekly</th>
<th class="key">Monthly</th>
</tr>
<tr>
<td class="value">10</td>
<td class="value">70</td>
<td class="value">300</td>
</tr>
</tbody>
<tfoot>
<tr>
<td class='display' colspan='3'></td>
</tr>
</tfoot>
</table>
You can also solve that using unique ids, like that:
$(document).ready(function() {
var str = '';
$('tbody > tr').each(function() {
$(this).find('.key').each(function() {
var index = $(this).attr('id').slice(3)
str += $(this).text() + ": " + $('#value'+index).text() + ", ";
})
});
console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th class="key" id="key1">Daily</th>
<th class="key" id="key2">Weekly</th>
<th class="key" id="key3">Monthly</th>
</tr>
<tr>
<td class="value" id="value1">10</td>
<td class="value" id="value2">70</td>
<td class="value" id="value3">300</td>
</tr>
</tbody>
</table>

KnockoutJS - show accumulate value for each item

How can I display in a table the accumulate value for each item in a observableArray with KnockoutJS?
I need somethin like:
function ViewModel(){
var self = this;
self.Item = function(day,note){
this.day = ko.observable(day);
this.note = ko.observable(note);
};
}
var itemsFromServer = [
{day:'Mo', note:1},
{day:'Tu', note:2},
{day:'We', note:3},
{day:'Th', note:4},
{day:'Fr', note:5},
{day:'Su', note:6},
];
var vm = new ViewModel();
var arrItems = ko.utils.arrayMap(itemsFromServer, function(item) {
return new vm.Item(item.day, item.note);
});
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr><th>Day</th><th>Note</th><th>Accumulate</th></tr>
</thead>
<tbody data-bind="foreach: arrItems">
<tr>
<td data-bind="text: day"></td>
<td data-bind="text: note"></td>
<td >the currente 'note' + the anterior 'note'</td>
</tr>
</tbody>
</table>
The last column should display the sum of current item + anterior item.
Thanks.
I'm not exactly sure what value you want the third column to be, but the main approach remains the same:
Give your Item class access to their "sibling items" by passing a reference to the array
In a computed property, do a "look behind" by looking up the items own index.
Perform some sort of calculation between two (or more) Item instances and return the value
For example, this acc property returns the acc of the previous Item and ones own note property:
var Item = function(day, note, siblings){
this.day = ko.observable(day);
this.note = ko.observable(note);
this.acc = ko.pureComputed(function() {
var allItems = siblings();
var myIndex = allItems.indexOf(this);
var base = myIndex > 0
? allItems[myIndex - 1].acc()
: 0
return base + this.note();
}, this);
};
function ViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.items(itemsFromServer.map(function(item) {
return new Item(item.day, item.note, self.items);
})
);
}
var itemsFromServer = [
{day:'Mo', note:1},
{day:'Tu', note:2},
{day:'We', note:3},
{day:'Th', note:4},
{day:'Fr', note:5},
{day:'Su', note:6},
];
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr>
<th>Day</th>
<th>Note</th>
<th>Accumulate</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: day"></td>
<td data-bind="text: note"></td>
<td data-bind="text: acc"></td>
</tr>
</tbody>
</table>

How to set index values to child rows in angular js

I have a requirement where I need to add index values for child rows. I have Group rows under which there will be child rows. I am ng-repeat and I am using $index for child's as shown:
HTML code:
<table ng-repeat="node in data">
<tr> <td> {{node.groupName}} </td> </tr>
<tbody ng-model="node.nodes">
<tr ng-repeat="node in node.nodes"> <td> {{$index}} </td> </tr>
</table>
But it is displaying as shown:
But I want it to display as shown:
I am new to Angular JS and not getting how to display it like this. How am I supposed to do that. Please help.
As far as I understood your question, you'd like to have something like that:
<table ng-repeat="group in data">
<thead>
<th> {{group.name}} </th>
</thead>
<tbody ng-repeat="item in group.items">
<tr>
<td>{{getIndex($parent.$index - 1, $index)}} | {{item}} </td>
</tr>
</tbody>
</table>
$scope.data = [
{name: 'Group1', items: ['a','b']},
{name: 'Group2', items: [1,2,3]},
{name: 'Group3', items: ['x', 'xx', 'xxx', 'xxxx']}
];
$scope.getIndex = function(previousGroupIndex, currentItemIndex){
if(previousGroupIndex >= 0){
var previousGroupLength = getPreviousItemsLength(previousGroupIndex);
return previousGroupLength + currentItemIndex;
}
return currentItemIndex;
};
function getPreviousItemsLength(currentIndex){
var length = 0;
for (var i = 0; i <= currentIndex; i++){
length += $scope.data[i].items.length;
}
return length;
// or even better to use Array.prototype.reduce() for that purpose
// it would be shorter and beautiful
// return $scope.data.reduce(function(previousValue, currentGroup, index){
// return index <= previousGroupIndex ? previousValue + currentGroup.items.length : previousValue;
// }, 0);
}
You need to play with $parent.$index property and use some math :) in order to achieve that.
It would look like the following:
Check out this JSFiddle to see live example.

Need regex filtering with angular-smart-table

I'm using angular smart table. Smart table has built in filtering using the st-search directive. However, I need some customized filtering using regular expressions.
I tried applying an angular filter to my data source (via the ng-repeat directive). While this works in regards to filtering, because smart table isn't aware of what i'm doing, it throws my paging off.
I've plunked an example of what is going on. (Try entering 1.8 in the account filter input box. You'll see the filter get applied but then if you click other pages, you'll see that they contain some of the filtered items as well.) I need the behavior to work similar to what happens if you filter by description (where filtered items get narrowed down and re-paged).
Here is my html table:
<table st-table="vm.accounts" class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th st-sort="account">Account</th>
<th st-sort="desc">Description</th>
<th>Current Balance</th>
<th> </th>
<th> </th>
</tr>
<tr class="warning">
<th>
<input placeholder="filter accounts" class="form-control input-sm" type="search" ng-model="vm.accountfilter" />
</th>
<th>
<input placeholder="filter description" class="form-control input-sm" type="search" st-search="desc" />
</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in vm.accounts | filter:vm.myfilter" ng-click="vm.selected = item" ng-class="{info: vm.selected == item}">
<td>{{item.account}}</td>
<td>{{item.desc}}</td>
<td>{{item.runbal | currency}}</td>
<td><button class="btn btn-danger btn-xs"><i class="fa fa-times-circle"></i></button></td>
<td><button class="btn btn-primary btn-xs"><i class="fa fa-pencil"></i></button></td>
</tr>
</tbody>
<tfoot>
<tr class="warning">
<td colspan="5" class="text-center">
<button class="btn btn-success btn-sm"><i class="fa fa-plus-circle"></i> Add new account</button>
</td>
</tr>
<tr>
<td colspan="5" class="text-center">
<div st-pagination="" st-items-by-page="20" st-displayed-pages="10"></div>
</td>
</tr>
</tfoot>
</table>
and here is the filter that I'm trying to apply (from my controller):
(function(){
'use strict';
angular.module("myapp", ["smart-table"])
.controller("mycontroller", MyController);
function MyController(){
var me = this;
me.accounts = [];
me.selected = null;
me.myfilter = myFilter;
me.accountfilter = '';
activate();
function activate(){
for(var x = 0; x < 6000; x++)
{
var build = '';
for(build; build.length < (12 / x.toString().length); build += x.toString()){}
var aclass = Math.floor((1800 - 1100 + 1) * Math.random() + 1100).toString();
var adept = Math.floor((800 - 100 + 1) * Math.random() + 100).toString();
var aincex = Math.floor(1001 * Math.random() + 4000).toString();
var asub = Math.floor(2 * Math.random());
var account = aclass + adept + aincex + (asub ? "AB" + x.toString() : "");
me.accounts.push({account: account, desc: "Text for " + x + " Account", runbal: x * 5, begbal: 5000, newbegbal: 20000, newrunbal: x * 7});
}
}
function myFilter(value, index, array){
if(!me.accountfilter) return true;
var valex = new RegExp("^[*0-9a-zA-Z.]{1,22}$");
if(me.accountfilter.match(valex))
{
var filter = me.accountfilter;
debugger;
filter = filter.replace(/\*/g,'\\w+');
filter = "^" + filter + ".*$";
var regex = new RegExp(filter,'i');
return value.account.match(regex)
}
else
return false;
}
}
})();
How can I "smart table enable" my filter?
My suspicions were correct. I'm not sure if this is the best way to do it, but here is how I accomplished the special filtering.
I made 3 change to my html.
I added st-pipe to my <table> element.
<table st-pipe="vm.pipe" st-table="vm.accounts" ... >
I removed the angular filter from my ng-repeat.
<tr ng-repeat="item in vm.accounts" ... >
I used the smart-table search feature on the account column (in place of the angular filter that I removed).
<input st-search="account" ... />
In my controller I then added the following:
...
var internalList = [];
me.pipe = Pipe;
function Pipe(tableState){
var perpage = tableState.pagination.number;
var start = tableState.pagination.start;
var filtered = internalList;
//If user has entered filter criteria
if(tableState.search.predicateObject)
{
//clone the filter criteria object
var myPred = $.extend({},tableState.search.predicateObject);
//remove the account criteria so I can process that myself
delete myPred["account"];
//perform the default filter function for any other filters
filtered = $filter('filter')(filtered, myPred);
//if user entered account (regex) filter then call my original filter function
if(tableState.search.predicateObject["account"])
{
filtered = $filter('filter')(filtered,myFilter);
}
}
//apply any sorting that needs to be applied
if (tableState.sort.predicate) {
filtered = $filter('orderBy')(filtered, tableState.sort.predicate, tableState.sort.reverse);
}
//set the bound array to the filtered contents
me.accounts = filtered.slice(start, start +perpage);
//clear the selected item if it is not included on the current page
if(me.accounts.indexOf(me.selected) < 0)
me.selected = null;
//Set the proper number of pages for our filtered list
tableState.pagination.numberOfPages = (filtered.length ? Math.floor(filtered.length / perpage) : 0);
}
Lastly, I had to change the activate function of my controller to populate the internalList rather than the display/bound list.
//me.accounts.push({account: account, desc: "Text for " + x + " Account", runbal: x * 5, begbal: 5000, newbegbal: 20000, newrunbal: x * 7});
internalList.push({account: ...});
You can see it in action here.

KnockoutJS - extending the shopping cart example

I'm currently trying to extend the KnockoutJS shopping cart example to preload existing rows from a JSON collection.
Say, I have an object like this:
var existingRows = [{
"Category":Classic Cars,
"Product":2002 Chevy Corvette,
"Quantity":1,
}, {
"Category":Ships,
"Product":Pont Yacht,
"Quantity":2,
}];
I am trying to modify the example so that on load it populates the grid with two rows, with the comboboxes pre-set to the items in the JSON object.
I can't seem to get this object playing nicely with JSFiddle, but I've got as far as modifying the Cart and CartLine functions, and ApplyBindings call as follows:
var CartLine = function(category, product) {
var self = this;
self.category = ko.observable(category);
self.product = ko.observable(product);
// other code
}
var Cart = function(data) {
var self = this;
self.lines = ko.observableArray(ko.utils.arrayMap(data, function(row) { return new CartLine(row.Category, row.Product);}))
// other code
}
ko.applyBindings(new Cart(existingRows));
This correctly inserts two rows on load, but does not set the drop down lists. Any help would be much appreciated :)
The problem is that the values of the category and product observables in the CartLine object are not simple strings. They are actual objects, e.g. category refers to a specific category from the sample data that's provided in that example, same with product.
But you're just setting them to strings.
(Another problem is that your JS object existingRows is not valid javascript because of quotes missing around the string)
To get that example working with your existingRows object you could extract the relevant category and product from the sample data:
var Cart = function(data) {
// Stores an array of lines, and from these, can work out the grandTotal
var self = this;
self.lines = ko.observableArray(ko.utils.arrayMap(data, function(row) {
var rowCategory = ko.utils.arrayFirst(sampleProductCategories, function(category) {
return category.name == row.Category;
});
var rowProduct = ko.utils.arrayFirst(rowCategory.products, function(product) {
return product.name == row.Product;
});
return new CartLine(rowCategory, rowProduct, row.Quantity);
}));
// other code
}
Updated fiddle: http://jsfiddle.net/antishok/adNuR/664/
<h1> Online shopping</h1>
<button id="btnAdd" data-bind='click: addLine'>Add product</button><br /><br />
<table width='100%'>
<thead>
<tr>
<th width='25%'>Product</th>
<th class='price' width='15%'>Price</th>
<th class='quantity' width='10%'>Quantity</th>
<th class='price' width='15%'>Subtotal (in rupees)</th>
<th width='10%'> </th>
</tr>
</thead>
<tbody data-bind='foreach: items'>
<tr>
<td>
<select data-bind='options: products, optionsText: "name", optionsCaption: "Select...", value: product'> </select>
</td>
<td class='price' data-bind='with: product'>
<span data-bind='text: (price)'> </span>
</td>
<td class='quantity'>
<input data-bind='visible:product, value: quantity, valueUpdate: "afterkeydown"' />
</td>
<td class='price'>
<span data-bind='visible: product, text: subtotal()' > </span>
</td>
<td>
<a href='#' data-bind='click: $parent.removeLine'>Remove</a>
</td>
</tr>
</tbody>
</table>
<h2>
Total value: <span data-bind='text: grandTotal()'></span> rupees
</h2>
$(document).ready(function () {
$("#btnAdd").button();
ko.applyBindings(new OnlineShopping());
});
function formatCurrency(value) {
return "$" + value.toFixed(2);
}
var Item = function () {
var self = this;
self.product = ko.observable();
self.quantity = ko.observable(1);
self.subtotal = ko.computed(function () {
var result = self.product() ? self.product().price * parseInt("0"+self.quantity(), 10) : 0;
return result;
});
};
var OnlineShopping = function () {
var self = this;
// List of items
self.items = ko.observableArray([new Item()]);
// Compute total prize.
self.grandTotal = ko.computed(function () {
var total = 0;
$.each(self.items(), function () { total += this.subtotal() })
return total;
});
// Add item
self.addLine = function () {
self.items.push(new Item())
};
// Remove item
self.removeLine = function () {
self.items.remove(this)
};
};
// Item collection
var products = [{ name: "IPhone", price: "45000" }, { name: "Galaxy Y", price: "7448" }, { name: "IPad", price: "25000" }, { name: "Laptop", price: "35000" }, { name: "Calci", price: "750"}];

Categories