angular building an array with a for loop - javascript

I'm building an array dynamically in a test angular app. Basically I have a scope function that generates an array of people and returns the array and I have an ng-repeat on the array. The array is not displaying but I'm not getting any errors in the console either, so idk what's up:
am I calling the getPerson function correctly? If there's a better way to do this do let me know.
heres the fiddle as well
$scope.person = {
firstname: "",
lastname: "",
isActive: true,
fullname: function() {
var personobject;
personobject = $scope.person;
return personobject.firstname
+ " "
+ personobject.lastname;
}
};
$scope.people = function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
};
$scope.getPerson = function(first, last, active) {
var newPerson = $scope.person;
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};

I've updated your fiddle here : https://jsfiddle.net/7j2khgbj/2/
var myapp = angular.module("myapp", []);
myapp.controller('appCont', function($scope) {
var Person = function(){
this.firstname = "";
this.lastname = "";
this.isActive = true;
};
Person.prototype.fullname = function() {
return this.firstname
+ " "
+ this.lastname;
};
var getPerson = function(first, last, active) {
var newPerson = new Person();
newPerson.firstname = first;
newPerson.lastname = last;
newPerson.isActive = active;
return newPerson;
};
$scope.addPerson = function() {
$scope.people.push({
firstname: $scope.person.firstname,
lastname: $scope.person.lastname
});
$scope.person.firstname = '';
$scope.person.lastname = '';
};
$scope.people = (function() {
var pplArray = [];
var firstnames = ['abdul','mahmud','gasser','ibtihaj','abudi'];
var lastnames = ['ahmad','samrai','badawi','jasim','ahmad'];
var actives = [true,true,false,true,false];
for (var i = 0; i < firstnames.length; i++) {
pplArray[i] = getPerson(firstnames[i], lastnames[i], actives[i]);
}
return pplArray;
})();
/*$scope.people = [
{firstname: 'abdul', lastname: 'ahmad'},
{firstname: 'mahmud', lastname: 'samrai'},
{firstname: 'gasser', lastname: 'badawi'},
{firstname: 'ibtihaj', lastname: 'jasim'},
{firstname: 'abudi', lastname: 'ahmad'},
{firstname: 'ahmad', lastname: 'jasim'},
{firstname: 'abdul', lastname: 'samrai'}
];*/
});
Some problems I saw:
1) $scope.people was a function, not an array (so I simply executed it and saved the result)
2) you were always overwriting the person (you need a Person class that creates new instances for the array element, not overwrite the same instance with new data - that way you'll get the same thing in all the array elements)
3) on $scope you should put things that need to be accessible from the view. Helper functions can just be local in the controller (if you don't want them as services, although as services they are reusable)
4) track by on ng-repeat (in case of duplicate keys)

Related

javascript document element by id

If I need to see my out put in the page not in console.log i want use document get Element By Id how can i do that? he gave me just one result, Steve only !!
[Code: ]
http://i.stack.imgur.com/ISqzT.png
<script>
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['Microsoft Way']
};
friends.steve = {
firstName: "Steve",
lastName: "Jobes",
number: "(444) 111 000",
address: ["Apple way"]
};
var list = function(obj) {
for( var key in obj){
console.log(obj);
document.getElementById("demo").innerHTML = key + "<br>";
}
}
var search = function(name) {
for(var key in friends){
if(name === friends[key].firstName){
console.log(friends[key]);
}
}
}
list(friends);
// search("Steve");
</script>
Hey the only change you have to make is using += instead of just = for the innerHTML function. Here you go:
text.innerHTML+=friend + "";
Simply append the result to your innerHTML, do not overwrite it, likewise:
document.getElementById("demo").innerHTML += key + "<br>";

Converting Javascript array objects to uppercase

var contacts =[];
function getInfo() {
var firstName = prompt("Enter first name");
var lastName = prompt("Enter last name");
var emailId = prompt("Enter Email ID");
var phoneNo = prompt("Enter Phone number");
var fname, lname, email, phone;
var person ={
fname : firstName,
lname : lastName,
email : emailId,
phone : phoneNo
}
contacts.push(person);
}
How do I convert contacts array to uppercase? After converting the array to uppercase, I want to display the full name in alphabetical order as shown in the picture. Or is there any other way to accomplish without converting to uppercase?
You can use this to convert a string to title casing:
function toTitleCase(str) {
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}
See example usage:
var nameMixedCaseing = ["alan bong" , "JusTin weasel", "Tom curry"]
for (i = 0; i < nameMixedCaseing.length; i++)
console.log(toTitleCase(nameMixedCaseing[i]));
Result is:
Alan Bong
Justin Weasel
Tom Curry
So in your code you can call this function before saving the person object
person.firstName = toTitleCase(person.firstName);
person.lastName = toTitleCase(person.lastName);
contacts.push(person);
You can use a combination of functions, one to capitalize, one to sort each time a new contact is pushed into the array:
var contacts = [
{
fname: 'andrew',
lname: 'mCGonahan'
},
{
fname: 'paUla',
lname: 'Ptrokva'
},
{
fname: 'kevin',
lname: 'harGRove'
},
{
fname: 'CAmille',
lname: 'dUpoIs'
},
{
fname: 'AlbERt',
lname: 'sWanson'
}
];
function capitalize(arr) {
for (var i = 0; i < arr.length; i++) {
var first = arr[i].fname;
var last = arr[i].lname;
arr[i].fname = first.slice(0,1).toUpperCase() + first.slice(1).toLowerCase();
arr[i].lname = last.slice(0,1).toUpperCase() +last.slice(1).toLowerCase();
}
return arr;
}
function sortByLast(arr) {
return arr.sort(function(a, b) {
if (a.lname > b.lname) return 1;
if (b.lname > a.lname) return -1;
return 0;
});
}
//you can call the following after you have pushed the newest contact into the array
// or you could capitalize the inputs as they are entered, then run the sort function on the contacts array
contacts = sortByLast(capitalize(contacts));
document.getElementById('sortedContacts').innerHTML = JSON.stringify(contacts);
<div id="sortedContacts"><h3></h3></div>

Convert URL params (inline and after ?) to object with JavaScript

I'm looking at creating a vanilla JavaScript function which creates an object of parameters from URL path definition given a specific URL path. Very similar to how AngularJS does it as part of the routeParams service. For example...
Given the following path definition:
/page1/{id}
And the actual URL path of:
/page1/23?fname=Jon&lname=Doe
I would like to create the following object:
{
"id": 23,
"fname": "Jon",
"lname": "Doe"
}
Any help would be greatly appreciated.
This is what I was looking for. It is a very rough example and the code could obviously be optimised and cleaned up however.
function getParams(route, path) {
var result = {};
var queryString = (path.indexOf("?") > -1) ? path.substr(path.indexOf("?") + 1, path.length) : null;
queryString.split("&").forEach(function(part) {
if(!part) return;
part = part.replace("+"," ");
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]");
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
var re = /{(\w+)}/g;
var results = [];
while (match = re.exec(route)) {
results.push(match[1]);
}
var re2 = /\/page1\/id\/(\w+)\/name\/(\w+)/g;
var results2 = re2.exec(path);
for (var i = 0; i < results.length; i++) {
result[results[i]] = results2[i + 1];
}
return result;
}
var route = "/page1/id/{id}/name/{name}";
var path = "/page1/id/23/name/leon?fname=Jon&lname=Doe";
var params = getParams(route, path);
console.log("PARAMS:", params);
The above code outputs:
PARAMS: Object {fname: "Jon", lname: "Doe", id: "23", name: "leon"}

adding to an array from a previous function

so I would like to access an an array i created in a previous function. and then in id1,id2,id3, i would Like to create a new property and give that property a value. I thought I have an idea of what I should do but what Im doing is not working. I get the error IdArray is undefined.
HTML:
<p id="show_me"></p>
<button onclick="ObjectArray()">click me</button>
<p id="added"></p>
<button onclick="Added()">Add</button>
javascript previous function:
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
var IdArray = [id1, id2, id3];
}
javascript new function:
function Added(IdArray, sex){
IdArray.push({sex : sex})
IdArray[0].sex = "male";
document.getElementById("added").innerHTML = IdArray[0];
}
im lost, so how do I access the array from the previous function and add to it?
You do not have access to variables in other functions, you can however access variable declared above your functions. Your real problem is a failure to understand Constructors, which will greatly benefit you in the future. Check this out:
function Employee(id, firstName, lastName, middleName){
this.id = id; this.firstName = firstName; this.lastName = lastName;
this.middleName = middleName;
this.notes = [];
this.getFullName = function(){
var mn = this.middleName ? ' '+this.middleName : '';
return this.firstName+mn+' '+this.lastName;
}
this.createNote = function(note){
this.notes.push(note);
return this;
}
this.getNotesString = function(delimiter){
return this.notes.join(delimiter);
}
}
var employee1 = new Employee('abc123', 'Joe', 'Schmoe');
employee1.createNote('Note You Want to Store.');
employee1.createNote('Just Another Test Note.');
var employee2 = new Employee('def456', employee1.firstName, 'Smith', 'Walter'); // notice how you access the other instance firstName
console.log(employee1.getFullName());
console.log(employee1.getNotesString('|'));
console.log(employee2.getFullName());
console.log(employee2.createNote('Note 1').createNote('Note 2').createNote('Note 3').getNotesString('|')); // by returning `this` you can access other methods in the same Constructor
You need to either save the IdArray or to return it:
var IdArray;
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
IdArray = [id1, id2, id3]; //removed the var keyword, so I am using the global variable
}
and then use it.
notice I removed the var keyword so I am using the global IdArray.
The variable IdArray was created inside the function, so it expires when the function ends. If you add the line
var IdArray;
before your first function that will make it global instead. Then reference to IdArray inside either function will refer to the same variable.
I added the IdArray as a property of the window object to give it global scope:
var ObjectArray = function() {
// object literal
var id1 = {
firstName: "John",
lastName: "Doe",
id: "12345"
};
// keyword new
var id2 = new Object;
id2.firstName = "Adam";
id2.lastName = "Bakely";
id2.id = "abcdef";
// object constructor
function employee(first, last, id) {
this.firstName = first;
this.lastName = last;
this.id = id;
}
var id3 = new employee("Dallas", "Star", "abc123");
//create an array
window.IdArray = [id1, id2, id3];
}

javascript constructors involving unknown amounts of arguments...

I was messing with some js on codecadamy and got a bit sidetracked trying to make something work.
In essence I was creating a few objects that are loaded into a controller object and set as properties of it with two functions that print the properties and compare a string to the name property of each object in the controller.
I noticed I can do it if I make the objects in the prototype style and specify a normal function to handle setting the properties like so:
var friends = {};
friends.setUp = function() {
this.friends = [];
for(var i in arguments) {
arguments[i].setUp();
this.friends.push(arguments[i]);
}
};
friends.list = function() {
for(var i in this.friends) {
console.log(this.friends[i]);
}
};
friends.search = function(name) {
for(var i in this.friends) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
var bill = {};
bill.setUp = function() {
this.firstName = "Bill";
this.lastName = "Gates";
this.number = "(206) 555-5555";
this.address = ['One Microsoft Way','Redmond','WA','98052'];
};
var steve = {};
steve.setUp = function() {
this.firstName = "Steve";
this.lastName = "Jobs";
this.number = "(206) 555-5555";
this.address = ['1 Infinite Loop','Cupertino','CA','95014'];
};
var mike = {};
mike.setUp = function() {
this.firstname = "Mike";
this.lastname = "Ryd";
this.number = "(800) 555-5555";
this.address = ['redacted'];
};
friends.setUp(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
However if I do it with constructors It does not work, example:
function bill() {
this.firstName = "Bill";
this.lastName = "Gates";
this.number = "(206) 555-5555";
this.address = ['One Microsoft Way','Redmond','WA','98052'];
};
function steve() {
this.firstName = "Steve";
this.lastName = "Jobs";
this.number = "(206) 555-5555";
this.address = ['1 Infinite Loop','Cupertino','CA','95014'];
};
function mike() {
this.firstname = "Mike";
this.lastname = "Ryd";
this.number = "(800) 555-5555";
this.address = ['redacted'];
};
function friends() {
this.friends = [];
for(var i in arguments) {
this.friends.push(arguments[i]);
}
};
friends.list = function() {
for(var i in this.friends) {
console.log(this.friends[i]);
}
};
friends.search = function(name) {
for(var i in this.friends) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
var bill = new bill();
var steve = new steve();
var mike = new mike();
var friends = new friends(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
I was wondering if this is a limitation of using constructors or am I messing up the syntax somewhere? Thank you!
This doesn't appear to have anything to do with constructors with an unknown number of arguments, but rather you are not assigning methods on your objects appropriately. They need to be put on the prototype so that they will be inherited by all objects that are created by this particular constructor. So in your code, these:
friends.list = function() {...}
friends.search = function() {...}
needs to be changed to:
friends.prototype.list = function() {...}
friends.prototype.search = function() {...}
Like this:
friends.prototype.list = function() {
for(var i = 0; i < this.friends.length; i++) {
console.log(this.friends[i]);
}
};
friends.prototype.search = function(name) {
for(var i = 0; i < this.friends.length; i++) {
if(this.friends[i].firstName === name) {
return this.friends[i];
}
}
};
Then, this code should work fine:
var bill = new bill();
var steve = new steve();
var mike = new mike();
var friends = new friends(bill, steve, mike);
friends.list();
var result = friends.search("Steve");
console.log(result);
And, then the code works as you would expect here: http://jsfiddle.net/jfriend00/ba4me8ua/
FYI, you'll noticed that I changed the way you iterate through the arguments object items to be more array-like and avoid any chance of getting any non-numeric properties in the iteration.

Categories