console.log string inside array object with angularjs - javascript

I want to console.log or target the string of an object inside array with angularjs but it doesn't work. Please help me I'm still new on angularjs.
Here is what I'm trying to do.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Profile Details AngularJS 1.X</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.6/angular.js"></script>
</head>
<body>
<div class="container" ng-app="DetailApp">
<div ng-controller="PostController">
</div>
</div>
<script>
var app = angular.module('DetailApp', []);
app.controller('PostController', function($scope) {
$scope.details = [{firstname: "Dave", lastname: "Del Rio"}, {firstname: "Gerald", lastname: "Kingston"}, {firstname: "Larry", lastname: "Jackson"}];
if ($scope.details.firstname == "Dave Del Rio") {
console.log("Hello Dave!")
}
else {
console.log("sorry, You're not welcome!")
};
});
</script>
</body>
</html>
I want to target the firstname "Dave" inside the array object but It doesn't work at all.

You can use Array#some to check if any element in an array matches a condition.
if ($scope.details.some(x => x.firstname === 'Dave' && x.lastname === 'Del Rio'))

Related

How to create a form for comments with the ability of dynamically adding them to the list?

I need to create a form for comments with the ability to dynamically add them to the list. Each comment should have an assigned ID in consecutive order. The newest comment should be at the very bottom. Comments should be stored in the comments array. Each comment should have properties such as id (number) and text (string). Comments array must be empty when loaded initially. Each click on the "Add" button should create a new object inside the array and create element in the DOM tree.
let nextId = 1;
const comments = [];
const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
const commentList = commentForm.querySelector('[data-id="comment-list"]');
button.addEventListener('click', () => {
const object = {};
if (commentInput.value != '') {
comments.map(() => ({ id: 'nextId++', text: commentInput.value }));
}
createElement();
});
function createElement() {
const newComment = document.createElement('li');
newComment.setAttribute('data-comment-id', comments.id);
newComment.textContent = comments.text;
commentList.appendChild(newComment);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="comment-form">
<textarea data-input="comment"></textarea>
<button data-action="add">Add</button>
</form>
<ul data-id="comment-list"></ul>
</div>
<script src="./js/app.js"></script>
</body>
</html>
There are some issues in your code:
You are trying to access commentList from commentForm, but that element is outside of the commentForm. Use document object to access the element.
comments is an array from which you are trying to access text property, there is text property on comments.
You should pass the current input value to the function so that you can set the newly created LI's text with the value.
You should use push() instead of map() to push an item into the array. nextId is a variable but you are using that as if it is a string, you should remove the quotes around it.
For the better user experience, I will suggest you to clear the value of the input after creating the item.
Demo:
let nextId = 1;
const comments = [];
const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
const commentList = document.querySelector('[data-id="comment-list"]');
button.addEventListener('click', () => {
const object = {};
if (commentInput.value != '') {
comments.push({ id: nextId++, text: commentInput.value });
}
createElement(commentInput.value);
commentInput.value = '';
});
function createElement(ci) {
const newComment = document.createElement('li');
newComment.setAttribute('data-comment-id', comments.id);
newComment.textContent = ci;
commentList.appendChild(newComment);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="comment-form">
<textarea data-input="comment"></textarea>
<button type="button" data-action="add">Add</button>
</form>
<ul data-id="comment-list"></ul>
</div>
<script src="./js/app.js"></script>
</body>
</html>

Output Random Value From Array

I have the following javascript code:
let gemStones = [
"Amethyst",
"Diamond",
"Emerald",
"Ruby",
"Sapphire",
"Topaz",
"Onyx",
];
let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
function findGems()
{
console.log("You found a " + randomGemStone + "!");
}
Here's the html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css.css">
<title>1. Gem Pond</title>
</head>
<body>
<h1>Gem Pond</h1>
<script src="main.js"></script>
<button id="gemPond_btn" onclick="findGems()">GET GEM</button>
</body>
</html>
When I click the "GET GEM" button several times in a row, I always get the same result instead of getting a random one.
I'm not sure what I'm doing wrong here.
Thanks in advance.
Move the let randomGemStone line into the findGems function:
function findGems()
{
let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
console.log("You found a " + randomGemStone + "!");
}
Otherwise you run it only once on page load and not every time you click the button.
let gemStones = [
"Amethyst",
"Diamond",
"Emerald",
"Ruby",
"Sapphire",
"Topaz",
"Onyx",
];
const findGems = () => {
let randomGemStone = gemStones[Math.floor(Math.random()*gemStones.length)];
console.log(`You found a ${randomGemStone}!`);
}
Note I have moved randomGemStone inside the function. Or the value will only be updated once when the script loads, this way it will be random everytime findGems() is called

Passing variable to Custom Svelte Web Component

I have created simple Custom Web Component using Svelte. It has been compiled and seems it should work well, but there is the difficulty. I'm trying to pass into prop some variable, but getting undefined all the time, but if I'm passing some string
Result.svelte component
<svelte:options tag="svelte-result" />
<script>
export let result = {metadata: {}, transfers: []};
export let string = 'no string';
</script>
<div class="result__wrapper">
{string}
<div class="result__metadata">
<div>{result.metadata.offset}</div>
<div>{result.metadata.limit}</div>
<div>{result.metadata.total}</div>
</div>
</div>
When it copiled I'm using it like
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Svelte test</title>
<script defer src="/svelte/wapi-client/svelte-component.js"></script>
</head>
<body>
<div id="test"></div>
</body>
<script>
const data = {
metadata: {
limit: 20,
offset: 0,
total: 311301
},
transfers: [
{
amount: "7.95",
identifier: "9cd9901f-44a5-4436-9aef-880354bbe2e4"
}
]
};
document.getElementById('test').innerHTML = `
<svelte-result string="works" result=${data}></svelte-result>`;
</script>
</html>
data variable not passed to component, but string passed and shown correctly... What Am I doing wrong? How can I pass data variable into component ?
You can't pass objects as attributes to custom elements. You need to stringify your object before passing it.
index.html
...
document.getElementById('test').innerHTML = `
<svelte-result string="works" result=${JSON.stringify(data)}></svelte-result>`;
...
Foo.svelte
<svelte:options tag="svelte-result" />
<script>
export let result = {metadata: {}, transfers: []};
export let string = 'no string';
$: _result = typeof result === 'string' ? JSON.parse(result) : result;
</script>
<div class="result__wrapper">
{string}
<div class="result__metadata">
<div>{_result.metadata.offset}</div>
<div>{_result.metadata.limit}</div>
<div>{_result.metadata.total}</div>
</div>
</div>
As an alternative to using JSON.stringify to pass the data to the component, you can pass it as a property rather than as an attribute — in other words instead of this...
document.getElementById('test').innerHTML = `
<svelte-result string="works" result=${data}></svelte-result>`;
...you do this:
document.getElementById('test').innerHTML = `
<svelte-result string="works"></svelte-result>`;
document.querySelector('svelte-result').result = data;
Not ideal, of course, since it means that you have to accommodate the initial undefined state and the post-initialisation state once result has been passed through, but web components are a bit awkward like that.

Typescript error - Property 'permission' not exists on type

I have this javascript code that shows the current status of notification permission:
main.js
var $status = document.getElementById('status');
if ('Notification' in window) {
$status.innerText = Notification.permission;
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>Current permission status is
<b id="status">unavailable</b>
</p>
<script src="/scripts/main.js"></script>
</body>
</html>
If I write the same code in a typescript file I am getting this error:
main.ts
var $status = document.getElementById('status');
if ('Notification' in window) {
$status.innerText = Notification.permission;
}
ERROR - Notification.permission
MESSAGE - Property 'permission' not exists on type
'new(title: string, options?: NotificationOptions): Notification;
prototype: Notification;
requestPermission(callback?: NotificationPermissionCallback):
Promise<string>;'
How to ignore this error?
Try casting Notification to the any type to avoid transpiler errors.
if ('Notification' in window) {
$status.innerText = (Notification as any).permission;
}
The other option is to include the Notification type's definition.

Display the result of a function as variable in a browser using document.getElementbyId.innerHTML in JavaScript

I am a newbie to JavaScript < 1 Week old
I wrote a very short HTML/JavaScript and got it to display on console.
Basically, I want to display the result of a function used as a variable inside the <p> tag of the HTML.
I got the script to display in the console.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
</script>
<script>
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
</script>
<p id="Kilograms"><!--I want the result here--></p>
</body>
</html>
How do I get the result of the function as a variable i.e var kilo (pounds)... to display in the p tag with id Kilograms?
Script shold be after BODY code, or you should add document ready event listener. So, try this solution:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p id="Kilograms"><!--I want the result here--></p>
</body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
document.getElementById("Kilograms").innerHTML = kilog(440);
</script>
</html>
Example in JSBin: https://jsbin.com/pacovasuve/edit?html,output
You can try this in your js code.
document.getElementById("Kilograms").innerHTML="write whatever you want here";
Try this
var p = document.getElementById('Kilograms');
p.innerHtml = 'any text';
// OR
p.innerHtml = kilog(440);

Categories