making calculation on property of the scope doesn't work - javascript

I'm very very new to Angular js concept so I have trouble with a calculation. I have a form where I'm expecting from user to enter a volume number. I would like to make a calculation and the result of this calculation will be a field for my mongo document. I can create mongo document but my calculation doesn't work. It always insert the original product volume, not the one after the calculation.
This is the object that will be a mongo document. I can fill types and tags array without problem.
$scope.product = {
types: [],
tags: []
};
Form group where I retrieve product volume
.form-group
label.col-sm-3.control-label Volume
.col-sm-4
input.form-control(
ng-model='product.volume',
type='number',
placeholder='Volume')
I have a submit button in my controller. Inside this submit button I'm creating a new product document for mongo and filling the values. I'm also doing my calculation inside this submit function.
var product = new Product($scope.product);
var capacity = 100
$scope.product.volume = (capacity / $scope.product.volume);
Finally after finishing my mongo document, I'm saving it.
product.$save(function ()...
What might be the problem?

It seems like you are creating the Product, and then editing the $scope.product. You should do the transformation on $scope.product.volume before creating the Product.
var product;
var capacity = 100;
$scope.product.volume = (capacity / $scope.product.volume);
product = new Product($scope.product);
product.$save(...);

Related

Trying to make a progress counter for a study buddy type website

The user fills out an input form with the number of pages and I want the user to be able to input the pages done (var pagesToBeSubtracted) and the function to subtract the pages and update it on the site.
function subtractPages() {
// Total pages that are grabbed from the input form
var totalPages = document.getElementById("numPages").value;
//Value of the input type number for done pages
var pagesToBeSubtracted = document.getElementById("donePages").value;
var remainingPages;
remainingPages = totalPages - pagesToBeSubtracted;
//Updating the number on the actual website
document.getElementById("pagesLeft").innerHTML = remainingPages;
However if you have total pages at 100 and you put that you did 5 pages it will go to 95 but if you press it again it will stay the same, if you bump it to 10 it will go down to 90 etc...
I get I should somehow save the result so that the next time the function is called, it doesn't start from the original number every time but from the updated one. But I can't figure out how to do it since I set the variable for total pages from the input form and every time the function is called it sets it at the same number again.
I'm sure I'm missing something elementary but I can't figure it out.
Once your user submit value in the input form, you can use localStorage to save that value. You can then access that value on user revisit to your website. localStorage store data locally within the user's browser. The data will not be deleted when the browser/computer is closed.
You can store a value by using setItem method of localStorage:
localStorage.setItem("totalPages", numberOfTotalPages);
localStorage.setItem("pagesToBeSubtracted", numberOfPagesToBeSubtracted);
You can get a stored value by using getItem method of localStorage
document.getElementById("pagesLeft").innerHTML = localStorage.getItem("totalPages")-localStorage.getItem("pagesToBeSubtracted");
For anyone that might be looking for the same solution, #Turnip did it I'm just copying and pasting his jsfiddle so that anyone next that comes can just see it.
https://jsfiddle.net/1n36wyf2/
var remainingPages = document.getElementById("numPages").value;
document.getElementById("btnSubtract").addEventListener("click", subtractPages);
// Update `remainingPages` when `#numPages` changes.
document.getElementById("numPages").addEventListener("input", function() {
remainingPages = this.value;
});
function subtractPages() {
var pagesToBeSubtracted = document.getElementById("donePages").value;
remainingPages = remainingPages - pagesToBeSubtracted;
//Updating the number on the actual website
document.getElementById("pagesLeft").innerHTML = remainingPages;
}

Returning a single child's value on Firebase query using orderByChild and equalTo

I am trying to pull a URL for an image in storage that is currently logged in the firebase real time database.
This is for a game of snap - there will be two cards on the screen (left image and right image) and when the two matches the user will click snap.
All of my image urls are stored in the following way:
Each one has a unique child called "index" - I also have another tree that is just a running count of each image record. So currently I am running a function that checks the total of the current count, then performs a random function to generate a random number, then performs a database query on the images tree using orderByChild and an equalTo that contains the random index number.
If I log the datasnap of this I can see a full node for one record (So index, score, url, user and their values) however if I try to just pull the URL I get returned a value of Null. I can, rather annoyingly, return the term "URL" seemingly at my leisure but I can't get the underlying value. I've wondered if this is due to it being a string and not a numeric but I can't find anything to suggest that is a problem.
Please bare in mind I've only been learning Javascript for about a week at max, so if I'm making obvious rookie errors that's probably why!
Below is a code snippet to show you what I mean:
var indRef = firebase.database().ref('index')
var imgRef = firebase.database().ref('images')
var leftImg = document.getElementById('leftImg')
var rightImg = document.getElementById('rightImg')
document.addEventListener('DOMContentLoaded', function(){
indRef.once('value')
.then(function(snapShot){
var indMax = snapShot.val()
return indMax;
})
.then(function(indMax){
var leftInd = Math.floor(Math.random()* indMax + 1)
imgRef.orderByChild('index').equalTo(leftInd).once('value', function(imageSnap){
var image = imageSnap.child('url').val();
leftImg.src=image;
})
})
})
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code needs to cater for that list, by looping over Snapshot.forEach():
imgRef.orderByChild('index').equalTo(leftInd).once('value', function(imageSnap){
imageSnap.forEach(function(child) {
var image = child.child('url').val();
leftImg.src=image;
})
})

adding list to array of list in localstorage

I have list of students like as follows form from user input form:
//student form input for 1st time
var student={name:"a",roll:"9",age:13}
//student form input for 2nd time
var student={name:"b",roll:"10",age:14}
//student form input for 3rd time
var student={name:"c",roll:"11",age:15}
Actually, i am developing phonegap applications. Each time the user submit form-input i.e. student information, I want to save them into localstorage. Finally, when online, i want to sync them. I know i can store them in localstorage as follows:
localStorage.setItem("studentinfo", JSON.Stringfy(student));
But, this will remove the first student info in the local storage when i save second student info.
Infact, when i save first, second and third input respectively, i want to add them in localstorage array and finally the result in localstorage should be like
key=studentlist,
value=[
{name:"a",roll:"9",age:13},
{name:"b",roll:"10",age:14},
{name:"c",roll:"11",age:15}
]
How can it be done in localstorage or phonegap localstorage?
You want to hold all your students in an array like this:
var students = [];
students.push({name:"a",roll:"9",age:13});
students.push({name:"b",roll:"10",age:14});
students.push({name:"c",roll:"11",age:15});
And then store that in localStorage:
localStorage.setItem('studentsInfo', JSON.stringify(students));
The best way to do that would be with a function like this:
// When you get more student information, you should:
var addNewStudent = function (name, roll, age) {
// retrieve it (Or create a blank array if there isn't any info saved yet),
var students = JSON.parse(localStorage.getItem('studentsInfo')) || [];
// add to it,
students.push({name: name, roll: roll, age: age});
// then put it back.
localStorage.setItem('studentsInfo', JSON.stringify(students));
}

How to get the row count from an azure database?

Am working on a windows store javascript application. The application uses data from azure mobile services.
Consider the below code:
var itemTable = mobileService.getTable('item');
//item is the table name stored in the azure database
The code fetches the entire table item and saves it to a variable itemTable.
What code will return the no of rows present in itemTable??
What you're looking for is the includeTotalCount method on the table/query object (unfortunately it's missing from the documentation, I'll file a bug to the product team to have it fixed).
When you call read on the query object, it will return by default 50 (IIRC, the number may be different) elements from it, to prevent a naïve call from returning all elements in a very large table (thus either incurring the outbound bandwidth cost for reserved services, or hitting the quota for free ones). So getting all the elements in the table, and getting the length of the results may not be accurate.
If all you want is the number of elements in the table, you can use the code below: returning zero elements, and the total count.
var table = client.getTable('tableName');
table.take(0).includeTotalCount().read().then(function (results) {
var count = results.totalCount;
new Windows.UI.Popups.MessageDialog('Total count: ' + count).showAsync();
});
If you want to query some elements, and also include the total count (i.e., for paging), just add the appropriate take() and skip() calls, and also the includeTotalCount as well.
If anybody comes here and interested in how to get the totalCount only on C# (like me), then this is how you do it:
var table = MobileService.GetTable<T> ();
var query = table.Take(0).IncludeTotalCount();
IList<T> results = await query.ToListAsync ();
long count = ((ITotalCountProvider)results).TotalCount;
Credit goes to this blog post here
You need to execute read() on the table query and then get the length of the results.
var items, numItems;
itemTable.read().then(function(results) { items = results; numItems = items.length; });
If you are only showing a record count and not the entire results - you should just select the ID column to reduce the amount of data transmitted. I don't see a count() method available yet in the JS Query API to fill this need.
var itemTable = mobileService.getTable('item').select('itemID');

store values from form to grid

I have create a add record form in extjs which stores user entered data into grid.
Well , if found following method to get form values from formPanel
var formPanel = new Ext.form.FormPanel({...});
var form = formPanel.getForm();
var firstName = form.findField('firstname').getValue();
but i want to covert all the user input value into JSON and want to store into Grid panel and want to send it to the server also. but using findField i have to manually create the array and then need to encode it into JSON , so is there any alternate way to directly read values from form and convert it into JSON and store it into Grid Panel.
When you say "want to store in the GridPanel" would you be updating an existing record in the Grid's store or would you be inserting a new one or both? (depending on whether its add or update probably?)
For such situations, BasicForm (var form in your snippet above) provides updateRecord( Record record ) method.
So your steps would be -
var record = Record.create(...) // in case of insert
OR
var record = //obtain record from grid.getStore() in case of update
Then,
formPanel.getForm().updateRecord(record); //update the passed record with values from the form
Followed by committing the record back to the store-
grid.getStore().add(record); //in case of insert
grid.getStore().commitChanges(); //incase of update
Reference - Ext.form.BasicForm , Ext.data.Record
Define your record type -
MyRecordType = Ext.data.Record.create(['id', 'field1', 'field2']);
var myrec = new MyrecordType();
Now pass myrec to updateRecord as mentioned above.

Categories