Accessing various elements in an array in Angular js - javascript

I am building an application using Angular js and Taffy DB.
javascript:
$scope.viewTable=function () {
$scope.resultlists=[];
$scope.resultSet=teamlist().get();
var teamdata=$scope.resultSet;
angular.forEach(teamdata,function(teamdata,i){
if (i<length) {
console.log(teamdata[i].text);
}
});
};
I have an array result from Taffy DB like this.
teamdata contains
[Object { text="zxcxzc", $$hashKey="00A", ___id="T000002R000002", more...}, Object { text="czxcz", $$hashKey="00C", ___id="T000002R000003", more...}, "zxczxc", Object { undefined={...}, ___id="T000002R000005", ___s=true}, 5454575, Object { undefined={...}, ___id="T000002R000007", ___s=true}, 2, 2727287.5]
and I have to display each element in a table.
How to access each element in the above array?
Please Advice

The signature of the angular.forEach for arrays is as follows:
angular.forEach(array, function(element) { ... })
So you should be able to access each row like that:
angular.forEach(teamdata, function(row) {
// ... row.text
});
angular.forEach documentation

Related

Is there a way to not include methods when converting an object to a json?

Right now, I'm trying to convert a object to a json, but the object has methods in it.
One common solution I've found is storing the function in the json, but that wouldn't work for me (mainly because that would totally break updating)
I think it will be easier to reinitialize the function every time the program is reloaded. What would be the best way to exclude functions when stringifying to json, but including the functions when the json is parsed?
Extra note: some of the functions are stored in arrays and other objects
Edit:
Current code to load json data:
var loadData = JSON.parse(window.localStorage.getItem("slotAuto"));
G = {
...G,
...loadData
};
Current code to save json data:
var toSave = JSON.stringify(G, G.ReplaceNull);
console.log(toSave);
window.localStorage.setItem("saveGame", toSave);
Replace Null function:
if (value == null) {
return undefined;
};
return value
Example object:
{
functionList: [function () {
console.log("do something")
}]
}
Example output:
{
"functionList": [null]
}

Ember.js how to remove object from array controller without ember data

I am trying to update the arraycontroller model after deleting a record using jquery ajax.I can add a new object using self.pushObject(data), but i cannot remove the object using self.removeObject(data). can someone please help. ("data" is the object that i removed, the server sends it back after removing it in server.)
removeTodo: function(id) {
var page_id = id;
self = this;
Ember.$.ajax({
url: url+id,
type: "DELETE"
}).then(function(data) {
self.removeObject(data);
});
}
data might have the same properties, but it isn't the object that exists in your array. See here, both of these objects look exactly alike, but they are different objects, and as such aren't equal.
{ foo : 7 } != { foo : 7 }
When removing from a collection, if you pass in the object to be removed, that object must exist in the collection.
You would want to first find the object, then remove it from the collection.
.then(function(data) {
var obj = self.findBy('id', id); // assuming the object has a property 'id'
self.removeObject(obj);
});

Copying object properties to new/another object using AngularJS

I'm wondering what is the best way of copying object property's from/to another object using AngularJS/JavaScript
Below is the Json object I'm getting:
{
"application":{
"number":"323-23-4231",
"amount":"234.44",
"ref_name":"Thomas Edison"
},
"borrower":{
"prefix":"Mr",
"first_name":"Eric",
"middle_name":"E",
"last_name":"Schulz",
"date_of_birth":"09/29/1975",
"email_address":"myemail#HOTMAIL.COM",
"phones":[
{
"number":"(555)555-5555",
"type":"Mobile"
}
]
}
}
Using the above Json object I want the new JSON object data to be looks like this:
{
"number":"323-23-4231",
"amount":"234.44",
"ref_name":"Thomas Edison",
"prefix":"Mr",
"first_name":"Eric",
"middle_name":"E",
"last_name":"Schulz",
"date_of_birth":"09/29/1975",
"email_address":"myemail#HOTMAIL.COM",
"phones":[
{
"number":"(555)555-5555",
"type":"Mobile"
}
]
}
If you have the original object in a variable called oldObj, you could do something like this (untested):
newObj = {}
newObj = angular.extend(newObj, oldObj.application)
newObj = angular.extend(newObj, oldObj.borrower)
There are lots of ways to copy the properties of one object to another in different frameworks. Angular has the built-in angular.extend which you can read about here
You could even do this without using any fancy methods:
newObj.number = oldObj.application.number
newObj.amount = oldObj.application.amount
newObj.ref_name = oldObj.application.ref_name
newObj.prefix = oldObj.borrower.prefix
...
But that'd be kinda silly :)

How to get current index in Array prototype map?

I'm using Array.prototype.map.call to store in an array a bunch of node list objects:
function getListings() {
return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
return {
rectangle: e.getBoundingClientRect();
}
}
}
However, I also want to store the order in which this elements appear in the DOM, and I don't know how to do that.
I know that I'm storing this in an array, and the order would be the index of the array. For example:
var listings = getListings();
console.log(listings[0]); // rank #1
console.log(listings[1]); // rank #2
// etc...
but I'm inserting the json object in a database, and the easiest way to store the "rank" information is by creating a property "rank" in my object, but I don't know how to get the "index" of the current array.
Something like:
function getListings() {
return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e) {
return {
rectangle: e.getBoundingClientRect(),
rank: magicFunctionThatReturnsCurrentIndex() // <-- magic happens
}
}
}
Any help pointing me to the right direction will be greatly appreciated! Thanks
The MDN documentation says:
callback is invoked with three arguments: the value of the element,
the index of the element, and the Array object being traversed.
So
function getListings() {
return Array.prototype.map.call(document.querySelectorAll('li.g'), function(e, rank) { // magic
return {
rectangle: e.getBoundingClientRect(),
rank: rank // <-- magic happens
}
}
}

Creating methods on the fly

Hi I'm trying to author a jQuery plugin and I need to have methods accessible to elements after they are initialized as that kind of object, e.g.:
$('.list').list({some options}); //This initializes .list as a list
//now I want it to have certain methods like:
$('.list').find('List item'); //does some logic that I need
I tried with
$.fn.list = function (options) {
return this.each(function() {
// some code here
this.find = function(test) {
//function logic
}
}
}
and several other different attempts, I just can't figure out how to do it.
EDIT:
I'll try to explain this better.
I'm trying to turn a table into a list, basically like a list on a computer with column headers and sortable items and everything inbetween. You initiate the table with a command like
$(this).list({
data: [{id: 1, name:'My First List Item', date:'2010/06/26'}, {id:2, name:'Second', date:'2010/05/20'}]
});
.list will make the <tbody> sortable and do a few other initial tasks, then add the following methods to the element:
.findItem(condition) will allow you to find a certain item by a condition (like findItem('name == "Second"')
.list(condition) will list all items that match a given condition
.sort(key) will sort all items by a given key
etc.
What's the best way to go about doing this?
If you want these methods to be available on any jQuery object, you will have to add each one of them to jQuery's prototype. The reason is every time you call $(".list") a fresh new object is created, and any methods you attached to a previous such object will get lost.
Assign each method to jQuery's prototype as:
jQuery.fn.extend({
list: function() { .. },
findItem: function() { .. },
sort: function() { .. }
});
The list method here is special as it can be invoked on two occasions. First, when initializing the list, and second when finding particular items by a condition. You would have to differentiate between these two cases somehow - either by argument type, or some other parameter.
You can also use the data API to throw an exception if these methods are called for an object that has not been initialized with the list plugin. When ('xyz').list({ .. }) is first called, store some state variable in the data cache for that object. When any of the other methods - "list", "findItem", or "sort" are later invoked, check if the object contains that state variable in its data cache.
A better approach would be to namespace your plugin so that list() will return the extended object. The three extended methods can be called on its return value. The interface would be like:
$('selector').list({ ... });
$('selector').list().findOne(..);
$('selector').list().findAll(..);
$('selector').list().sort();
Or save a reference to the returned object the first time, and call methods on it directly.
var myList = $('selector').list({ ... });
myList.findOne(..);
myList.findAll(..);
myList.sort();
I found this solution here:
http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html
This seems to do exactly what I need.
(function($) {
var TaskList = function(element, options)
{
var $elem = $(element);
var options = $.extend({
tasks: [],
folders: []
}, options || {});
this.changed = false;
this.selected = {};
$elem.sortable({
revert: true,
opacity: 0.5
});
this.findTask = function(test, look) {
var results = [];
for (var i = 0,l = options.tasks.length; i < l; i++)
{
var t = options['tasks'][i];
if (eval(test))
{
results.push(options.tasks[i]);
}
}
return results;
}
var debug = function(msg) {
if (window.console) {
console.log(msg);
}
}
}
$.fn.taskList = function(options)
{
return this.each(function() {
var element = $(this);
if (element.data('taskList')) { return; }
var taskList = new TaskList(this, options);
element.data('taskList', taskList);
});
}
})(jQuery);
Then I have
$('.task-list-table').taskList({
tasks: eval('(<?php echo mysql_real_escape_string(json_encode($tasks)); ?>)'),
folders: eval('(<?php echo mysql_real_escape_string(json_encode($folders)); ?>)')
});
var taskList = $('.task-list-table').data('taskList');
and I can use taskList.findTask(condition);
And since the constructor has $elem I can also edit the jQuery instance for methods like list(condition) etc. This works perfectly.
this.each isn't needed. This should do:
$.fn.list = function (options) {
this.find = function(test) {
//function logic
};
return this;
};
Note that you'd be overwriting jQuery's native find method, and doing so isn't recommended.
Also, for what it's worth, I don't think this is a good idea. jQuery instances are assumed to only have methods inherited from jQuery's prototype object, and as such I feel what you want to do would not be consistent with the generally accepted jQuery-plugin behaviour -- i.e. return the this object (the jQuery instance) unchanged.

Categories

Resources