Model in Angular.js - javascript

Here is my code
/// <reference path="angular.min.js" />
var myApp = angular.module("myModule", []).controller("myController", function($scope) {
var employees = [{
name: "Ben",
dateOfBirth: new Date("November 23,1980"),
gender: "Male",
salary: 55000.788
}, {
name: "Sara",
dateOfBirth: new Date("May 05,1970"),
gender: "Female",
salary: 68000
}, {
name: "Mark",
dateOfBirth: new Date("August 15,1974"),
gender: "Male",
salary: 57000
}, {
name: "Pam",
dateOfBirth: new Date("October 27,1979"),
gender: "Female",
salary: 53000
}, {
name: "Todd",
dateOfBirth: new Date("December 30,1983"),
gender: "Male",
salary: 60000
}];
$scope.employees = employees;
$scope.sortColumn = "name";
$scope.reverseSort = false;
$scope.sortData = function(column) {
$scope.reverseSort = ($scope.sortColumn == column) ? !$scope.reverseSort : false;
$scope.sortColumn = column;
}
$scope.getSortClass = function(column) {
if ($scope.sortColumn == column)
return $scope.reverseSort ? 'arrow-down' : 'arrow-up';
return '';
}
});
I just want to ask that are employees,sortColumn and reverse sort are separate models or they belong to one model and what are the sortData and getSortClass in this files are they behavior in our model please explain...Thanks in advance.

SortData, contains the column name from which you want to sort and the reverseSort is a property of current employee object, which is set to true once the sort order is descending ( binary 0 ).
getSortClass fetch the current sort order in binary format ( 0 or 1) and update the reverseSort property accordingly.

Where to start... The variables in your codeblock all belong to the myController controller you have defined. They are instantiated when the controller is invoked through the $scope dependency, as well as any injected dependencies there may be.
sortData and getSortClass are functions declared in the scope of your controller. You cannot access them from another controller unless you traverse angulars $rootScope or using a listener. As for what those functions do, #kapil yadav has given an explanation.

Related

JavaScript need a way to clean up JSON.Stringify without modifying a helper function

Working on an assignment. I am using .filter() to find a list of active members. Following the instructions of the assignment the output is very messy. I would like to only display the member names or the member _ids.
This is the helper function and I cannot modify this function. As a rule of the assignment.
const printKata = function (kataNumber, object) {
const detailsElement = document.createElement("details");
main.append(detailsElement);
const summaryElement = document.createElement("summary");
summaryElement.append("KATA " + kataNumber);
detailsElement.append(summaryElement);
const stringifiedObject = JSON.stringify(object);
detailsElement.append(stringifiedObject);
...
Here is an example of the user object
const users = [
{
_id: "5efb83d333dadb00fc5f68e4",
isActive: true,
balance: "$2,967.17",
picture: "http://placehold.it/32x32",
age: 21,
eyeColor: "green",
name: "Gregory Villarreal",
company: "BLUPLANET",
email: "undefined.undefined#bluplanet.name",
phone: "+1 (866) 544-2326",
registered: "Friday, May 24, 2019 3:08 PM",
tags: ["quis", "irure", "consequat", "ut", "occaecat"],
}
...
And here is the simple function to filter the data.
let userActive = users.filter(function (user) {
return user.isActive === true;
});
...
Currently it is displaying all the data from the entire object. I think it would look a lot nicer to only display the name and or id ..
I am very new to all of this. Please be patient with me.
Currently it is displaying all the data from the entire object. I
think it would look a lot nicer to only display the name and or id ..
To do that, Use map just after your filter method, to specify only fields you want from objects and not all of them.
const users = [{
_id: "5efb83d333dadb00fc5f68e4",
isActive: true,
balance: "$2,967.17",
picture: "http://placehold.it/32x32",
age: 21,
eyeColor: "green",
name: "Gregory Villarreal",
company: "BLUPLANET",
email: "undefined.undefined#bluplanet.name",
phone: "+1 (866) 544-2326",
registered: "Friday, May 24, 2019 3:08 PM",
tags: ["quis", "irure", "consequat", "ut", "occaecat"],
}]
let userActive = users.filter(function(user) {
return user.isActive === true;
}).map(({id,name})=>({id,name}));
console.log(userActive)
This function is returning what you are asking from it:
let userActive = users.filter(function (user) {
return user.isActive === true;
});
"Filter the users array and return the user where isActive is true."
The return is the user object (or users if there is more than one) with all the key/value pairs.
As suggested in the previous answer, you can chain the map method at the end and return the values you want.

Iterating through object properties/keys

I'm just starting to learn coding, and i came across this question that i could not understand.
"The second function we'll add will be called search, and it will take a first name as an argument. It will try to match the first name it receives to any of the first names in our friends contact list. If it finds a match, it will log our friend's contact information (firstName, lastName, number, address) to the console."
variables are define as follows :
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
the answer is as follows :
var search = function(name) {
for(var key in friends) {
if(friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
};
could someone better explain how did the var "key" came about ? and why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
would appreciate if someone could explain thank you.
From OP's comment:
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
friends is a nested object which can also be represented like so:
friends = {
bill: {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
},
steve: {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
}
}
The for..in loop iterates over all keys in the friends object, with the variable key in your case.
why can't i just input friends.firstName === name, console.log(friends.name), return friends.name ??
Because, to do that, you need to have firstName or name as a property in friends. Since those properties are nested inside (name is not event inside the nested objects), there was a for..in loop used.
You have an object friends that has 2 properties bill and steve (those are the keys). Calling friends.bill will return you an object (the value) with firstname, lastname, number, address. You need to iterate all the properties of your object friends to find the one you need
You can use Object.values(obj)
var firstNameInput = "Steve";
var friends = {};
friends.bill = {
firstName: "Bill",
lastName: "gates",
number: "1234567",
address: ['bishan','starbucks', 'centertable']
};
friends.steve = {
firstName: "Steve",
lastName: "jobs",
number: "987654",
address: ['orchird', 'ikoma', 'ga']
};
//Iterates all the friends
Object.values(friends).forEach(function(f){
//Compare the property "firstname" with the input
if(f.firstName === firstNameInput){
//Friend found
console.log(f);
return;
}
});

JavaScript build a dynamic object

I have a var named onversation that contains this:
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
I also have an object named person that contains this:
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
What I'd like is to have a combined object called result that looks like this
result {
conversation {
conversationId : adbabc54-3308-436d-a48b-932f4010d3c6,
participantId : 415651e6-f0a5-4203-8019-4f88c3ed9cd5
},
person {
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
}
How would I do this dynamically whereby the result object is built using the name of the var 'conversation' and name of the object 'person' ?
Also, the length of either conversation or person can be any length.
Pure JavaScript if possible , but could use underscore etc.
Try it
var result = {
'conversation': conversation,
'person': person
}
Dynamic
var result = {}
result['person'] = person
or
resilt.person = person
If I understand your question correctly, you can use object shorthand notation which is supported in most browsers (Probably all of them, except IE11) for simplifying your solution even more:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { conversation, person }
console.log(result)
EDIT:
If only the variable name changes, and it's properties names stay the same or have some sort of unique key, you can use a for loop on the object's keys.
For example:
var someConversationVariableName =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var somePersonVariableName =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = { someConversationVariableName, somePersonVariableName }
for (key in result) {
if(result[key]['conversationId']) {
console.log(`Found conversation object. It's name is: ${key}`);
}
else if(result[key]['firstname']) {
console.log(`Found person object. It's name is: ${key}`);
}
}
If you need to defer adding objects, you can also take this approach:
var conversation =
{
conversationId : 'adbabc54-3308-436d-a48b-932f4010d3c6',
participantId : '415651e6-f0a5-4203-8019-4f88c3ed9cd5'
};
var person =
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
};
var result = {};
result['conversation'] = conversation;
result['person'] = person;
console.log(result);
This Must work :-
var conversation =
{
"conversationId": "adbabc54-3308-436d-a48b-932f4010d3c6",
"participantId": "415651e6-f0a5-4203-8019-4f88c3ed9cd5"
}
var person=
{
firstname: "fred",
surname: "smith",
age: "21",
gender: "male"
}
var result = {
'conversation': conversation,
'person': person
}

AngularJS: Call JSON array value in nested Controller

How to call Json array value in other controller. Basically i work with nested controller. Nested controller will return first character of firstname and lastname.
For example if my first name is Anand Jee then It will return AJ, Rohan Kumar then it will return RK.
My AngularJS code.
//create module
var myApp = angular.module("myApp", []);
//create controller
myApp.controller("empCtrl", function ($scope) {
var Employees = [
{ FirstName: "Anand", LastName: "Jee", Roles: "Web Developer", Technology: ".NET" },
{ FirstName: "Pritus", LastName: "Dubey", Roles: "Window App Developer", Technology: "XAMARIN" },
{ FirstName: "Vineet", LastName: "Rai", Roles: "Web Developer", Technology: ".NET" },
{ FirstName: "Nilesh", LastName: "Pathak", Roles: "UI/UX Developer", Technology: "Photoshop" },
{ FirstName: "Vikesh", LastName: "Juyal", Roles: "Web Developer", Technology: "PHP" }
];
$scope.Employees = Employees;
});
myApp.controller("EmpShortName", function ($scope) {
$scope.getEmpShortName = function () {
//$scope.empShortName = $scope.Employees.FirstName + " " + $scope.Employees.LastName;//here is problem
$scope.empShortName = "NP";//For temp declaration
return $scope.empShortName;
};
});
PLUNKER DEMO
Pass the Employee object into the getEmpShortName function. Then just return the parsed value. Also, no need for the EmpShortName controller, just put the scope function in your empCtrl controller:
HTML:
<div class="empTextImage">{{getEmpShortName(emp)}}</div>
JS:
$scope.getEmpShortName = function (emp) {
return emp.FirstName.substr(0,1) + emp.LastName.substr(0,1);
};
Updated Plunker

Clean Method to Normalize Javascript Object Properties

I have an array of javascript objects that represent users, like so:
[
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
]
Some of the objects contain some properties but not others. What I need is a clean way to ensure ALL objects get the same properties. If they don't exist, I want them to have an empty string value, like so:
[
{ userName: "Michael",
city: "Boston",
state: "",
phone: ""
},
{ userName: "Thomas",
city: "",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
city: "",
state: "",
phone: "444-4444"
}
]
Update
I should have been a little more specific. I was looking for an option that would handle this situation dynamically, so I don't have to know the properties ahead of time.
For jQuery specific, the $.extend() option is a good one, but will only work if you know ALL the properties ahead of time.
A few have mentioned that this should probably be a server-side task, and while I normally agree with that, there are two reasons I'm not handling this at the server-side:
1) it will be a smaller JSON object if say 900 of 1000 objects only contain 1 of a possible 9 properties.
2) the "empty" properties need to be added to satisfy a JS utility that could be replaced in the future with something that doesn't care if some properties are missing.
Since you are using jQuery you can abuse $.extend
function Person(options){
return $.extend({
userName:"",
city: "",
state:"",
phone: ""
},options);
}
$.map([{}],Person)
update
Heres a way to have dynamic default properties
function mapDefaults(arr){
var defaultProperties = {}
for(var i =0; i < arr.length; i++){
$.each(arr[i],function(key){
defaultProperties[key] = "";
});
}
function Defaulter(obj){
return $.extend({},defaultProperties,obj);
}
return $.map(arr, Defaulter);
}
mapDefaults([{a:"valA"},{b:"valB"}]);
/* produces:
[{a:"valA",b:""},{a:"",b:"valB"}]
*/
Something you might try is creating a coalescing function:
function coalesceValues(val){
switch(val)
case undefined:
case null:
return '';
break;
default:
return val;
break;
}
}
Or if you wanted to forego customization for simplicity:
function coalesceValues(val){
return val || '';
}
And then apply it when assigning variables:
var city = coalesceValues(obj.city);
This way you don't need to do any crazy breakdown to array and loop or anything, you can apply it to whatever you want, and you can also customize the values you want to coalesce.
Just offering an alternative idea.
The way that is easiest to understand is probably to make a function that accepts an object and uses if statements as existence checks, assigning a default value if it doesn't find it.
function normalize(object) {
if(typeof object.userName === 'undefined') {
object.userName = 'Default Value';
}
if(typeof object.city === 'undefined') {
object.city = 'Default Value';
}
if(typeof object.state === 'undefined') {
object.state = 'Default Value';
}
if(typeof object.phone === 'undefined') {
object.phone = 'Default Value';
}
return object;
}
var userArray = [{},{},{}].map(normalize);
We can also go the constructor route and provide default values on object creation.
function User (data) {
this.userName = data.userName || 'Default Value';
this.city = data.city || 'Default Value';
this.state = data.state || 'Default Value';
this.phone = data.phone || 'Default Value';
return this;
}
var userArray = [{},{},{}].map(function(o){
return new User(o);
});
Of course this depends on one specific type of data and won't extend to other properties and isn't very DRY, but as I said, this is probably the easiest to understand from a beginner's standpoint.
var list = [
{ userName: "Michael",
city: "Boston"
},
{ userName: "Thomas",
state: "California",
phone: "555-5555"
},
{ userName: "Kathrine",
phone: "444-4444"
}
];
for(var i = 0; i < list.length; i++){
if(list[i].state === undefined)
list[i].state = "";
if(list[i].phone === undefined)
list[i].phone = "";
};
console.log(list);
http://jsfiddle.net/g5XPk/1/
This should probably be a server-side task, but..
If you know all the possible properties ahead of time, you could do this:
http://jsfiddle.net/BMau9/
var properties = ['userName', 'city', 'state', 'phone'];
var data = [{
userName: "Michael",
city: "Boston"
}, {
userName: "Thomas",
state: "California",
phone: "555-5555"
}, {
userName: "Kathrine",
phone: "444-4444"
}];
for (var i in data) {
for (var j in properties) {
data[i][properties[j]] = data[i][properties[j]] || '';
}
}
Fiddle
This function stores unique object keys in an array and so you can run your array of objects through it and then use one of the other supplied answers to add the keys to the objects if they do not exist:
function uniqueKeys(){
var keys=[];
function getUniqueKeys(){
return keys
}
function addObject(obj){
for (var k in obj){
keys = _.union(keys,[k]);
}
}
return {
addObj: addObject,
getKeys: getUniqueKeys
}
}
Usage:
var objArr = [{ userName: "Michael", city: "Boston" },
{ userName: "Thomas", state: "California", phone: "555-5555"},
{ userName: "Kathrine",phone: "444-4444" }];
var uniq = new uniqueKeys();
_.each(objArr, function(v){
uniq.addObj(v)
});
var keys = uniq.getKeys();
alert(keys);
vanilla js
let A = [
{
userName: "Michael",
city: "Boston",
},
{
userName: "Thomas",
state: "California",
phone: "555-5555",
},
{
userName: "Kathrine",
phone: "444-4444",
},
];
// set-difference
const diff = (a,b) => new Set([...a].filter((x) => !b.has(x)));
// all keys
const K = new Set(arr.map(o => Object.keys(o)).flat());
// add missing keys and default vals
A.forEach((e,i) => diff(K, new Set(Object.keys(e))).forEach(k => A[i][k] = ""));

Categories

Resources