How to push element in array of JSON - javascript

This is my controller from which I am requesting to POST the data on server. While I am able to POST title and rating, i am unable to POST any genres because Genres is an array. How to push the data in Genres Array?
app.controller('addTrack', function ($scope, $http) {
$scope.tracks = [];
var genre = [];
var pushing = genre.push($scope.add_genre);
$scope.add_track = "";
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function (response) {
$scope.tracks = response.data.results;
});
$scope.add = function (event) {
if (event.keyCode == 13) {
$http.post('http://104.197.128.152:8000/v1/tracks', {
title: $scope.add_title,
rating: $scope.add_rating,
})
.then(function (data) {
$scope.genres = data;
//console.log($scope.add_genre);
$scope.add_title = '';
$scope.add_rating = '';
$scope.add_genre = '';
});
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function (response) {
$scope.genres = response.data.results;
});
}
} });
Http POST to http://104.197.128.152:8000/v1/tracks
Accepted response
{
"title": "animals",
"rating": 4.5,
"genres": [
1
]
}
Providing you my HTML as well.
<!DOCTYPE html>
<html ng-app="musicApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-controller="addTrack">
<div>
<h1>Add New Track</h1>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" class="form-control" ng-model="add_title" placeholder="Type to add new Title">
</div>
<div class="form-group">
<label>Genre:</label>
<input type="text" class="form-control" ng-model="add_genre" placeholder="Type to add new Genre">
</div>
<div class="form-group">
<label>Rating:</label>
<input type="text" class="form-control" ng-model="add_rating" placeholder="Type to add new Rating" ng-keyup="add($event)">
</div>
<div class="clearfix">
<button class="btn btn-primary col-xs-12 bottom-button" value="click" id="button">Add a New Track</button>
</div>
<div class="clearfix">
<label>Available Tracks</label>
<ul class="list-group" ng-repeat="track in tracks">
<li class="list-group-item clearfix"><span class="pull-left title">{{track.title}}</span> <span class="genre">[{{track.genres[0].name}}]</span> <span class="pull-right rating">{{track.rating}}</span></li>
</ul>
</div>
</div>
</body>
</html>

If what you are trying to achieve is to add a track object with title, rating and genre, you need to change your whole logic so your controller will bind all inputs to the same object properties.
First you need to define a track object in your controller, and bind the inputs to its properties in your HTML:
JavaScript:
app.controller('addTrack', function($scope, $http) {
$scope.tracks = [];
$scope.track = {
title: '',
rating: 0,
genre: ''
};
$http.get('http://104.197.128.152:8000/v1/tracks?page=48')
.then(function(response) {
$scope.tracks = response.data.results;
});
$scope.add = function(event) {
if (event.keyCode == 13) {
$http.post('http://104.197.128.152:8000/v1/tracks', $scope.track)
.then(function(data) {
$scope.track = {};
});
}
}
});
HTML:
<!DOCTYPE html>
<html ng-app="musicApp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<div class="container" ng-controller="addTrack">
<div>
<h1>Add New Track</h1>
</div>
<div class="form-group">
<label>Title:</label>
<input type="text" class="form-control" ng-model="track.title" placeholder="Type to add new Title">
</div>
<div class="form-group">
<label>Genre:</label>
<input type="text" class="form-control" ng-model="track.genre" placeholder="Type to add new Genre">
</div>
<div class="form-group">
<label>Rating:</label>
<input type="text" class="form-control" ng-model="track.rating" placeholder="Type to add new Rating" ng-keyup="add($event)">
</div>
<div class="clearfix">
<button class="btn btn-primary col-xs-12 bottom-button" value="click" id="button">Add a New Track</button>
</div>
</div>
</body>
</html>
Note:
Note the use of ng-model="track.title", ng-model="track.rating"
and ng-model="track.genre" in the HTML to bind these inputs to our
trackobject properties.
This code assumes that genre will be a string here, if you will use a
list of object you need to amend your code so it fits this option.

Related

Covid-19 error message when country isn't entered isn't matched with API

I'm developing a COVID-19 tracker app so far it works but I'm having issue for when the user search for a country that isn't in the API a error message is suppose to pop up as the else statement, which indeed it does happen. The issue is the message would pop up when a country that's been entered and the API has the info the error message would still pop up. Any advice would help, thank you.
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if(getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
else {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
break;
}
}
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>
The else part is replaced. If countriesIndex is not updated from 0 , that means the data is not found.
Fixed Code:
let btn = document.getElementById("submit-btn");
//set variable btn to the html button id
btn.addEventListener("click",()=>{
let text = document.getElementById("input-text").value;
console.log("button was pressed");
//added a event once btn is pressed taking the value of what was typed in the form
fetch('https://api.covid19api.com/summary')
.then((covidData)=>{
return covidData.json();
})
//
.then((getData)=>{
console.log(getData);
console.log("api was contacted");
var content = document.querySelector(".api-data");
var box = content.lastElementChild;
while (box) {
content.removeChild(box);
box = content.lastElementChild;
}
var countriesIndex = 0;
for(var i = 0; i < 185; i++){
if( getData.Countries[i].Country.toLowerCase() == text.toLowerCase()){
countriesIndex = i;
break;
}
}
if(countriesIndex==0) {
var hideData = document.querySelector(".api-data");
hideData.style.display = "none";
alert("No information for that country")
}
else{
let data = document.querySelector(".api-data");
data.innerHTML = `<div class="data-boxes">
<div class="country-index">
<span>Covid-19 Cases in ${getData.Countries[countriesIndex].Country}</span>
</div>
<div class="total-data">
<div><p>Total Confirmed</p> ${getData.Countries[countriesIndex].TotalConfirmed}</div>
<div><p>Total Deaths</p> ${getData.Countries[countriesIndex].TotalDeaths}</div>
<div><p>Total Recovered</p> ${getData.Countries[countriesIndex].TotalRecovered}</div>
</div>
<div class="new-data">
<div><p>New Confirmed</p> ${getData.Countries[countriesIndex].NewConfirmed}</div>
<div><p>New Deaths</p> ${getData.Countries[countriesIndex].NewDeaths}</div>
<div><p>New Recovered</p> ${getData.Countries[countriesIndex].NewRecovered}</div>
</div>
</div>`;
}
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/css2?family=News+Cycle:wght#400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="container tracker-container">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="covid-header">Covid-19 Daily Tracker</h1>
<p class="covid-description">A daily tracker of the Covid-19 virus, enter the country in the search bar to recieve the report.</p>
<p class="covid-description">Report is given from the "covid19api" API.</p>
</div>
</div>
<div class="info-box">
<form>
<div class="form-row input-row">
<div class="col-12 form">
<label for="country-input">Enter country's name</label>
<input type="text" class="form-control" id="input-text" value="" required>
<button type="button" class="btn btn-success btn-block" id="submit-btn">Get Statistics</button>
</div>
</div>
</form>
<div class="api-data">
</div>
</div>
</div>
</body>
<script src="tracker.js"></script>
</html>

Reuse function to delete an item

I want to make a button that adds and removes items.
The 'Delete form' button changes to 'Add form' after click it.
But after I've deleted and added forms, I want to delete forms again, but for reasons I don't understand, it doesn't happen.
I'm using the latest chrome browser version.
<!DOCTYPE html>
<html lang="en" style="height: 100%">
<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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<title>Task 1</title>
</head>
<body style="height: 100%">
<div class="container h-100">
<div class="row h-100 justify-content-center align-content-center">
<div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
<div class=""><button type="button" class="btn btn-danger" id="danger">Delete form</button></div>
<div class="breaker w-100" style="height:10%;"></div>
<form id="form">
<div class="form-group">
<label for="formGroupExampleInput">Example label</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Another label</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
</div>
</form>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
document.getElementsByClassName('btn-danger')[0].addEventListener("click", delete_function);
let inner_form = document.getElementById('form').innerHTML;
function open_google() {
window.open('http://google.com', '_blank');
}
let buttons;
function button_change(button) {
switch(button) {
case "success":
buttons = document.getElementsByClassName('btn');
buttons[1].innerHTML = 'Add form';
buttons[1].className = 'btn btn-success';
document.getElementsByClassName('btn-success')[0].addEventListener("click", add_function);
break;
case "danger":
buttons = document.getElementsByClassName('btn');
buttons[1].innerHTML = 'Delete form';
buttons[1].className = 'btn btn-danger';
break;
default:
break;
}
}
function delete_function() {
let element = document.getElementById('form');
while (element.firstChild) {
element.removeChild(element.firstChild);
}
button_change("success");
}
function add_function() {
document.getElementById('form').innerHTML = inner_form;
button_change("danger");
}
Example code: https://codepen.io/anon/pen/xNjPYj
The event listeners aren't being removed, so both functions are being called (potentially multiple times) depending on how many times the buttons are clicked.
Personally, I think it would be easier to create two buttons, each with independent click handlers, and hide/show them according to which one was clicked.
However, to resolve the current issue in your code, you'll need to remove the previous event listener using removeEventListener() before attaching the new one.
Why don't you just hide it? This is much easier
function toggle() {
var element = document.getElementById("form");
if (element.style.display === "none") {
element.style.display = "block";
}
else {
element.style.display = "none";
}
}
<!DOCTYPE html>
<html lang="en" style="height: 100%">
<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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<title>Task 1</title>
</head>
<body style="height: 100%">
<div class="container h-100">
<div class="row h-100 justify-content-center align-content-center">
<div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
<div class=""><button onclick="toggle()" type="button" class="btn btn-danger" id="danger">Delete form</button></div>
<div class="breaker w-100" style="height:10%;"></div>
<form id="form">
<div class="form-group">
<label for="formGroupExampleInput">Example label</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Another label</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
</div>
</form>
</div>
</div>
</body>
</html>
The main issue with your code was that the event listeners kept getting added but not removed, this caused them to pile up and run unpredictably. I added a function that determines what state the button is in and performs the correct function add_function or remove_function.
I also changed a few minor things
Now usesinnerHTML to textContent where possible for security
Button classes are updated using button.classList.add and button.classList.remove
The button is found using an ID instead of an unreliable classname
The button is held in a variable instead of continuing the look for it
Removed the button_change function because it was difficult to refactor
https://codepen.io/anon/pen/BexJZW
JavaScript:
document.getElementsByClassName('btn-primary')[0].addEventListener("click", open_google);
let inner_form = document.getElementById('form').innerHTML;
let add_delete_button = document.querySelector('#add-delete-button');
add_delete_button.addEventListener("click", on_add_delete_clicked);
function open_google() {
window.open('http://google.com', '_blank');
}
function on_add_delete_clicked() {
let is_adding = add_delete_button.classList.contains("btn-success");
if (is_adding) {
add_function();
} else {
delete_function();
}
}
function add_function() {
const button = add_delete_button;
document.getElementById('form').innerHTML = inner_form;
// Update button
button.textContent = 'Delete form';
button.classList.remove("btn-success");
button.classList.add("btn-danger");
}
function delete_function() {
let element = document.getElementById('form');
while (element.firstChild) {
element.removeChild(element.firstChild);
}
// Update button
const button = add_delete_button;
button.textContent = 'Add form';
button.classList.remove("btn-danger");
button.classList.add("btn-success");
}
HTML:
<!DOCTYPE html>
<html lang="en" style="height: 100%">
<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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<title>Task 1</title>
</head>
<body style="height: 100%">
<div class="container h-100">
<div class="row h-100 justify-content-center align-content-center">
<div class=""><button type="button" class="btn btn-primary">Open Google</button></div>
<div class=""><button type="button" class="btn btn-danger" id="add-delete-button">Delete form</button></div>
<div class="breaker w-100" style="height:10%;"></div>
<form id="form">
<div class="form-group">
<label for="formGroupExampleInput">Example label</label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input">
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Another label</label>
<input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input">
</div>
</form>
</div>
</div>
<script src="./index.js"></script>
</body>
</html>
This implementation will do the text and context switching you desire.
function action(mouseevent) {
const button = mouseevent.target;
let element = document.getElementById('form');
if(element.firstChild) {
while (element.firstChild) {
element.removeChild(element.firstChild);
}
button.innerHTML = 'Add form';
button.classList.remove('btn-danger');
button.classList.add('btn-success');
} else {
document.getElementById('form').innerHTML = inner_form;
button.innerHTML = 'Delete Form';
button.classList.add('btn-danger');
button.classList.remove('btn-success');
}
}

How do I make this loop print the values I need?

I'm rather new to Javascript, so please excuse simple mistakes if I made any. I need to make a task board page. The user inputs a value (a task and a date) and JS saves it into an object. The object is pushed into an array and saved to Local Storage. After that, it fades in a note (did this with an image and CSS effects) and prints the value on top of it. To accomplish this I tried using a For loop to go through the array when I get it back from local storage, but it only keeps printing the first value the user entered.
This is my code:
var taskArray = [];
var imgs = document.getElementsByTagName("img");
$(document).ready(function hideImages() {
$("img").hide();
})
function saveToLocalStorage() {
//debugger;
var taskName = document.getElementById("task").value;
var taskDate = document.getElementById("date").value;
var task = {
name: taskName,
date: taskDate
}
taskArray.push(task);
var arrayToString = JSON.stringify(taskArray);
localStorage.setItem("user tasks", arrayToString);
var mainDiv = document.getElementById("maindiv");
var arrayFromStorage = localStorage.getItem('user tasks');
arrayFromStorage = JSON.parse(arrayFromStorage);
for (let index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML += `
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan">
Your task = ${arrayFromStorage[x].name}
Complete by = ${arrayFromStorage[x].date}
</span>
`
x++
addText();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" integrity="sha384-B4dIYHKNBt8Bc12p+WXckhzcICo0wtJAoU8YZTY5qE0Id1GSseTk6S+L3BlXeVIU" crossorigin="anonymous">
<title></title>
</head>
<body class="background-image">
<h1 class="pageheader">My Task Board</h1>
<form class="" action="index.html" method="post">
<div class="container">
<div class="row">
<input type="text" class="form-control col-sm centerInput" id="task" placeholder="Enter a Task">
<input type="date" class="form-control col-sm centerInput" id="date" value="">
</div>
<div class="form-group">
<input type="button" class="form-control btn btn-success" id="submit" value="Submit Task" onclick="saveToLocalStorage()">
</div>
<div class="form-group">
<input type="reset" class="form-control btn btn-success " id="reset" value="Reset Form">
</div>
</div>
</form>
<div class="imgContainer" id="maindiv">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript" src="scripts.js"></script>
<!-- load the script at the end of body tag -->
</body>
</html>
Any help would be greatly appreciated, cheers!
Try putting index instead of x in your loop.
for (let index = 0; index < arrayFromStorage.length; index++) {
mainDiv.innerHTML +=
`
<span class="relative">
<img src="../assets/images/notebg.png" class="fade-in start imgSpacing" alt="">
<span class="centerOnNote" id="textspan">
Your task = ${arrayFromStorage[index].name}
Complete by = ${arrayFromStorage[index].date}
</span>
`
}

Vue cloning issue

I am learning vue and one of the things I would like to do is to clone elements. I was playing with this code:
var multiple = new Vue({
el: '#vue',
data: {
},
methods: {
cloneWidget(e) {
let widgets = document.getElementById('widgets');
let widget = document.getElementById('widget');
clone = widget.cloneNode(true);
clone.id = Math.round(Math.random()*100);
widgets.appendChild(clone);
},
deleteClone(e) {
e.target.parentNode.remove();
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="styles.css" rel="stylesheet" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
</head>
<body>
<h1>Cloning</h1>
<div id="vue">
<form #submit.prevent>
<div id="widgets">
<div id="widget">
<div>
<label for="field1">Field 1:</label>
<input type="text" name="field1">
</div>
<div>
<label for="field2">Field 2:</label>
<input type="text" name="field2">
</div>
<i class="material-icons delete" #click="deleteClone">delete</i>
</div>
</div>
<button #click="cloneWidget">Add Widget</button>
</form>
</div>
<script src="app.js"></script>
</body>
</html>
However, the deleteClone method never gets called outside the original div="widget".
I can't seem to figure out why the event listener is not getting attached to the clones. Will cloneNode() mess up Vue?
With Vue, generally you want to think in terms of data. Here is your example revised, such that a widget is rendered for each object in the widgets array.
In this case, the contents of the array don't make much sense; you would probably want to the properties of each object in the array to match your input fields, but this is just an example to get you going.
var multiple = new Vue({
el: '#vue',
data: {
widgets:[{}]
},
methods: {
addWidget() {
this.widgets.push({})
},
removeWidget(widget) {
this.widgets.splice(this.widgets.findIndex(w => w === widget), 1)
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" rel="stylesheet"/>
<h1>Cloning</h1>
<div id="vue">
<form #submit.prevent>
<div id="widgets">
<div v-for="widget in widgets">
<div>
<label for="field1">Field 1:</label>
<input type="text" name="field1">
</div>
<div>
<label for="field2">Field 2:</label>
<input type="text" name="field2">
</div>
<i class="material-icons delete" #click="removeWidget(widget)">delete</i>
</div>
</div>
<button #click="addWidget">Add Widget</button>
</form>
</div>
For the most part, you want to stay away from manipulating the DOM directly and let Vue do the work for you.

Laravel + AngularJS controller is existing but returns an error of not a function

Im just new to AngularJS and would like to integrate it using Laravel (5.2)
I was able to successfully load Laravel and Angular in this manner.
HTML File: ../resources/views/master.php
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript" src="assets/js/phone-app/app.module.js"></script>
</head>
<body>
<div class="container" ng-app="todoApp">
<div class="row">
<div class="col-md-12">
<h2>Todo</h2>
<div ng-controller="TodoListController as todoList">
<span>{{todoList.remaining()}} of {{todoList.todos.length}} remaining</span>
[ archive ]
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
</li>
</ul>
<form ng-submit="todoList.addTodo()">
<input type="text" ng-model="todoList.todoText" size="30" placeholder="add new todo here">
<input class="btn-primary" type="submit" value="add">
</form>
</div>
</div>
</div>
</div>
</body>
</html>
AngularJS File: ../public/assets/js/phone-app/app.module.js
(function() {
'use strict';
angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
todoList.todos = [
{text:'learn angular', done:true},
{text:'build an angular app', done:false}];
todoList.addTodo = function() {
todoList.todos.push({text:todoList.todoText, done:false});
todoList.todoText = '';
};
todoList.remaining = function() {
var count = 0;
angular.forEach(todoList.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
todoList.archive = function() {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
});
})();
But when I created a separate html that will accommodate angular templates, this is when I get an error of Argument 'TodoListController' is not a function, got undefined
Here's the structure:
HTML File: ../resources/views/master.php
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript" src="assets/js/phone-app/app.module.js"></script>
</head>
<body>
<div class="container" ng-app="todoApp">
<div class="row">
<div class="col-md-12">
<todo-app></todo-app>
</div>
</div>
</div>
</body>
</html>
AngularJS File: ../public/assets/js/phone-app/app.module.js
(function() {
'use strict';
angular.module('todoApp', []);
angular.module('todoApp')
.component('todoApp', {
templateUrl: 'assets/js/phone-app/templates/todo.html',
controller: function TodoListController() {
var todoList = this;
todoList.todos = [
{text:'learn angular', done:true},
{text:'build an angular app', done:false}];
todoList.addTodo = function() {
todoList.todos.push({text:todoList.todoText, done:false});
todoList.todoText = '';
};
todoList.remaining = function() {
var count = 0;
angular.forEach(todoList.todos, function(todo) {
count += todo.done ? 0 : 1;
});
return count;
};
todoList.archive = function() {
var oldTodos = todoList.todos;
todoList.todos = [];
angular.forEach(oldTodos, function(todo) {
if (!todo.done) todoList.todos.push(todo);
});
};
}
}
);
})();
Template File: ../public/assets/js/phone-app/templates/todo.html
<h2>Todo</h2>
<div ng-controller="TodoListController as todoList">
<span>{{todoList.remaining()}} of {{todoList.todos.length}} remaining</span>
[ archive ]
<ul class="unstyled">
<li ng-repeat="todo in todoList.todos">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
</li>
</ul>
<form ng-submit="todoList.addTodo()">
<input type="text" ng-model="todoList.todoText" size="30" placeholder="add new todo here">
<input class="btn btn-primary" type="submit" value="add">
</form>
</div>
If you'll notice, I moved the content on a separate template file. This loads the page with the template but returns an error on the console and just displays the page as is.
I was able to get this work but somehow don't know how this works. #_#
Anyway, I just tried to search for examples on the AngularJS site and tried to "copy" them. With that, I have arrived with this solution.
On the template file, I removed the ng-controller and change all the todoList with $ctrl.
<h2>Todo</h2>
<div>
<span>{{$ctrl.remaining()}} of {{$ctrl.todos.length}} remaining</span>
[ archive ]
<ul class="unstyled">
<li ng-repeat="todo in $ctrl.todos">
<label class="checkbox">
<input type="checkbox" ng-model="todo.done">
<span class="done-{{todo.done}}">{{todo.text}}</span>
</label>
</li>
</ul>
<form ng-submit="$ctrl.addTodo()">
<input type="text" ng-model="$ctrl.todoText" size="30" placeholder="add new todo here">
<input class="btn btn-primary" type="submit" value="add">
</form>
</div>
Will someone please explain to me how did the $ctrl worked in here and why the ng-controller is not necessary in this kind of structure versus the first one I stated above?
Try to replace
.component
with
.directive
Maybe components have a bug

Categories