i have two button function
sort for most like and most recent
This is just simulation, could be hardcoded
how do i link the button with the function.
This is the source code from one of the source.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="UTF-8" />
</head>
<body>
<button onclick="function1">Sort Most Like</button>
<button onclick="function2">Sort Most Recent</button>
<div id="app"></div>
<script src="src/index.js">
</script>
</body>
</html>
<script>
const imgArr = [
{ src: "https://unsplash.it/300/225?image=0", Recent: "24/1/2018", Likes: 6 },
{ src: "https://unsplash.it/300/225?image=0", Recent: "24/3/2018", Likes: 2 },
{ src: "https://unsplash.it/300/225?image=0", Recent: "25/1/2018", Likes: 3 },
{ src: "https://unsplash.it/300/225?image=0", Recent: "24/2/2018", Likes: 1 },
];
const html = imgArr.sort((a, b) => {
return a.Likes + b.Likes
}).map(imageItem => {
return `<figure class="einzel"><img alt="Mitglieder" src=${
imageItem.src
} style="width: 315px; height: 250px;">
<figcaption>Name: ${imageItem.Name}<br>
<span>Likes: ${imageItem.Likes}</span></figcaption>
</figure>`;
});
document.getElementById("app").innerHTML = html;
</script>
The code below includes the function to sort the entries by likes in ascending order.
const imgArr = [{
src: "https://unsplash.it/300/225?image=0",
Recent: "24/1/2018",
Likes: 6
},
{
src: "https://unsplash.it/300/225?image=0",
Recent: "24/3/2018",
Likes: 2
},
{
src: "https://unsplash.it/300/225?image=0",
Recent: "25/1/2018",
Likes: 3
},
{
src: "https://unsplash.it/300/225?image=0",
Recent: "24/2/2018",
Likes: 1
},
];
/* Gemeric function to display array content on screen */
const init = (ar) => ar.map(el => {
return `<figure class="einzel"><img alt="Mitglieder" src=${
el.src
} style="width: 315px; height: 250px;">
<figcaption>Recent: ${el.Recent}<br>
<span>Likes: ${el.Likes}</span></figcaption>
</figure>`;
});
const sortByLikes = (a, b) => {
if (a.Likes === b.Likes) {
return 0;
}
return a.Likes > b.Likes ? 1 : -1;
};
/* Generate array sorted by number of likes ascending */
const function1 = () => {
document.getElementById("app").innerHTML = init([...imgArr].sort(sortByLikes));
}
document.getElementById("app").innerHTML = init(imgArr);
<button onclick="function1()">Sort Most Like</button>
<button onclick="function2">Sort Most Recent</button>
<div id="app"></div>
Related
I am trying to create a v-for that shows a list of exercises containing several sets. I have created a loop with a row for each set underneath each exercise.
my data looks like this.
const exercises = [
{ id: 1, name: exercise1, sets: 3 },
{ id:2, name: exercise2, sets: 2 }
{ id:3, name: exercise3, sets: 4 }
]
And my component looks something like this:
<template v-for="exercise in exercises" :key="exercise.id">
<span> {{ exercise.name }} </span>
<template v-for="set in exercise.sets" :key="set">
<span #click="completeSet()"> {{ set }} </span>
</template>
</template>
Now I want to be able to mark each set as completed by setting the value on each set to either true or false through a click event. But I am not sure about how to do this since each set doesn't have a property to set a value because it's looping through a number.
What would be the right approach to this problem?
First and foremost, you can't loop through a number. To be able to loop the sets, you'd have to
<template v-for="let set = 0; set < exercise.sets; set++" :key="set">
<span #click="completeSet()"> {{ set }} </span>
</template>
However, setting a property on a number is equally impossible. You have to prepare your data to be able to make that adjustment:
const exercises = [
{ id: 1, name: 'exercise1', sets: 3 },
{ id: 2, name: 'exercise2', sets: 2 } ,
{ id: 3, name: 'exercise3', sets: 4 }
].map(exercise => ({
id: exercise.id,
name: exercise.name,
sets: Array.from(
{ length: exercise.sets },
() => ({ completed: false })
),
}))
You can create array with finished sets and compare it (try the snippet pls):
new Vue({
el: "#demo",
data() {
return {
exercises: [{ id: 1, name: 'exercise1', sets: 3 }, { id: 2, name: 'exercise2', sets: 2 }, { id: 3, name: 'exercise3', sets: 4 }],
finishedSets: []
}
},
computed: {
checkAll() {
return this.exercises.reduce((acc, curr) => acc + curr.sets, 0) === this.finishedSets.length
}
},
methods: {
compareObjects(o1, o2) {
return Object.entries(o1).sort().toString() !== Object.entries(o2).sort().toString()
},
findObject(id, set) {
return this.finishedSets.find(f => f.id === id && f.set === set)
},
completeSet(id, set) {
this.findObject(id, set) ?
this.finishedSets = this.finishedSets.filter(f => {return this.compareObjects(f, this.findObject(id, set))}) :
this.finishedSets.push({id, set})
},
isFinished(id, set) {
return this.findObject(id, set) ? true : false
},
}
})
.set {
width: 70px;
cursor: pointer;
}
.finished {
background-color: seagreen;
}
.finished__not {
background-color: tomato;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div v-for="exercise in exercises" :key="exercise.id">
<span> {{ exercise.name }} </span>
<div v-for="set in exercise.sets" :key="set">
<div #click="completeSet(exercise.id, set)" class="set" :class="isFinished(exercise.id, set) ? 'finished' : 'finished__not'"> {{ set }} <span>
<span v-if="isFinished(exercise.id, set)">finished</div>
</div>
</div>
<button v-if="checkAll">submit</button>
<p>{{finishedSets}}</p>
</div>
I want a user to be able to put his info about their book and push it into the library. I can do this when it comes to display but I want to have it saved as a new object in javascript. A new array 'newBooks' that I created don't return a new value, it stays the same even though I used spread operator which is supposed to change the value. Could someone tell me what's going on?
const booksContainer = document.querySelector('.booksContainer');
const buttonNewBook = document.querySelector('.buttonNewBook');
const buttonConfirm = document.querySelector('.confirmBook')
const inputContainer = document.querySelector('.addNewBook');
buttonNewBook.addEventListener('click', () => {
if (inputContainer.style.display === 'none') {
inputContainer.style.display = 'flex'
} else {
inputContainer.style.display = 'none'
}
if (buttonConfirm.style.display === 'none') {
buttonConfirm.style.display = 'inline'
} else {
buttonConfirm.style.display = 'none'
}
});
const books = [
{
id: 1,
imageUrl: '',
title: 'Title:',
author: 'Author:',
pages: 'Pages:'
},
{
id: 5, imageUrl: '',
id: 6, title: 'Title:',
id: 7, author: 'Author:',
id: 8, pages: 'Pages:'
},
{
id: 9, imageUrl: '',
id: 10, title: 'Title:',
id: 11, author: 'Author:',
id: 12, pages: 'Pages:'
},
{
id: 13, imageUrl: '',
id: 14, title: 'Title:',
id: 15, author: 'Author:',
id: 16, pages: 'Pages:'
}
]
books.forEach((book, index) => {
let booksDisplay = document.createElement('div')
booksDisplay.setAttribute('class', 'booksDisplay')
booksContainer.appendChild(booksDisplay)
let booksDisplayImage = document.createElement('img');
booksDisplayImage.src = (`${book.imageUrl}`)
booksDisplayImage.setAttribute('class', 'booksImage');
booksDisplay.appendChild(booksDisplayImage);
let imageContainer = document.createElement('div')
imageContainer.setAttribute('class', 'imageContainer');
booksDisplay.appendChild(imageContainer);
imageContainer.appendChild(booksDisplayImage)
let booksDisplayTextTitle = document.createElement('p');
booksDisplayTextTitle.setAttribute('class', 'titleText')
let booksDisplayTextAuthor = document.createElement('p');
booksDisplayTextAuthor.setAttribute('class', 'authorText')
let booksDisplayTextPages = document.createElement('p');
booksDisplayTextPages.setAttribute('class', 'pagesText')
let booksDisplayTextDisplayTitle = document.createTextNode(`${book.title}`);
booksDisplayTextTitle.appendChild(booksDisplayTextDisplayTitle);
let booksDisplayTextDisplayAuthor = document.createTextNode(`${book.author}`);
booksDisplayTextAuthor.appendChild(booksDisplayTextDisplayAuthor)
let booksDisplayTextDisplayPages = document.createTextNode(`${book.pages}`);
booksDisplayTextPages.appendChild(booksDisplayTextDisplayPages);
let textContainer = document.createElement('div');
textContainer.setAttribute('class', 'textContainer');
booksDisplay.appendChild(textContainer);
textContainer.appendChild(booksDisplayTextTitle);
textContainer.appendChild(booksDisplayTextAuthor);
textContainer.appendChild(booksDisplayTextPages);
booksContainer.appendChild(booksDisplay);
let buttonRead = document.createElement('button')
let buttonRemove = document.createElement('button');
buttonRemove.addEventListener('click', () => {
booksDisplayTextTitle.textContent = 'Title:';
booksDisplayTextAuthor.textContent = 'Author:';
booksDisplayTextPages.textContent = 'Pages:';
booksDisplayImage.style.display = 'none';
imageContainer.style.border = '1px solid rgb(107, 107, 107)'
});
let buttonReadText = document.createTextNode ('I have read this book');
let buttonRemoveText = document.createTextNode ('Remove a book');
buttonRead.appendChild(buttonReadText);
buttonRemove.appendChild(buttonRemoveText);
textContainer.appendChild(buttonRead)
textContainer.appendChild(buttonRemove)
});
const inputTitle = document.querySelector('#title');
const inputAuthor = document.querySelector('#author')
const inputPages = document.querySelector('#pages')
const inputImageUrl = document.querySelector('#imageUrl')
inputImageUrl.value = '';
inputTitle.value = '';
inputAuthor.value = '';
inputPages.value = '';
const titleText = document.querySelector('.titleText');
const authorText = document.querySelector('.authorText');
const pagesText = document.querySelector('.pagesText');
const bookImageUrl = document.querySelector('.booksImage');
console.log(inputTitle)
buttonConfirm.addEventListener('click', () => {
bookImageUrl.src = inputImageUrl.value;
titleText.textContent = 'Title:' + ' ' + inputTitle.value;
authorText.textContent = 'Author:' + ' ' + inputAuthor.value;
pagesText.textContent = 'Pages:' + ' ' + inputPages.value;
const newBooks = books.map(newBook => {
if (newBook.id == 1) {
return {...newBook, author: inputAuthor.value, title: inputTitle.value, pages: inputPages.value}
}
return newBook;
});
console.log(newBooks)
});
console.log(books)
<!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="./styles/style.css">
<title>Document</title>
</head>
<body>
<div class="myLibrary">
<form class="addNewBook">
<input type="text" name="titles" id="title" placeholder="Title">
<input type="text" name="author" id="author" placeholder="Author">
<input type="number" name="pages" id="pages" placeholder="Number of pages">
<input type="link" name="imageUrl" id="imageUrl" placeholder="Image URL">
</form>
<div class="buttonContainer">
<button class="buttonNewBook">Add a new book</button>
<button class="confirmBook">Confirm</button>
</div>
<div class="booksContainer">
</div>
<script src="./scripts/script.js"></script>
</body>
</html>
Your book is wrong formated
let info = {
id: 1, imageUrl: '',
id: 2, title: 'Title:',
id: 3, author: 'Author:',
id: 4, pages: 'Pages:'
}
console.log( info )
is the same as
let info = {}
info.id = 1
info.id = 2
info.id = 3
info.id = 4
info.title = ....
there could be only one info.id propertie
I lost time understanding the purpose of your code, but I suggest you get inspired by this way of coding...
const
newBookForm = document.forms['add-New-Book']
, books =
[ { id: 1, imageUrl: '', title: 'Title-1', author: 'Author:', pages: 'Pages:' }
, { id: 2, imageUrl: '', title: 'Title-2', author: 'Author:', pages: 'Pages:' }
, { id: 3, imageUrl: '', title: 'Title-3', author: 'Author:', pages: 'Pages:' }
, { id: 4, imageUrl: '', title: 'Title-4', author: 'Author:', pages: 'Pages:' }
]
, booksContainer = document.querySelector('.booksContainer')
, newBook = { id: books.reduce((r,{id})=>Math.max(r,id),0) }
;
function displayNewBook(book)
{
let booksDisplay = document.createElement('div')
booksDisplay.className = 'booksDisplay'
booksDisplay.innerHTML = `
<div class="imageContainer">
<img src="${book.imageUrl}" class="booksImage" >
</div>
<div class="textContainer">
<p class"titleText">${book.title}</p>
<p class"authorText">${book.author}</p>
<p class"pagesText">${book.pages}</p>
<button data-op="readed" data-ref="${book.id}"> I have read this book</button>
<button data-op="remove" data-ref="${book.id}"> Remove this book</button>
</div>`
booksContainer.appendChild(booksDisplay)
}
books.forEach( displayNewBook )
;
newBookForm.onsubmit = e => e.preventDefault() // disable form submit for no page relaoding
;
newBookForm.onclick = ({target: bt }) =>
{
if (!bt.matches('button')) return;
let addBook = (bt.name==='btAdd')
if ( addBook && !newBookForm.checkValidity() )
{
newBookForm.reportValidity()
return
}
newBookForm.btAdd .classList.toggle('noDisplay', addBook )
newBookForm.btConfirm.classList.toggle('noDisplay', !addBook )
newBookForm.btCancel .classList.toggle('noDisplay', !addBook )
newBookForm.titles .readOnly = addBook
newBookForm.author .readOnly = addBook
newBookForm.pages .readOnly = addBook
newBookForm.imageUrl.readOnly = addBook
if (bt.name==='btConfirm')
{
let book =
{ id : ++newBook.id
, imageUrl : newBookForm.imageUrl.value
, title : newBookForm.titles.value
, author : newBookForm.author.value
, pages : newBookForm.pages.value
}
books.push( book )
displayNewBook( book )
newBookForm.reset()
console.clear()
console.log ( 'books:\n' + JSON.stringify(books).replaceAll('},{','}\n,{') )
}
}
booksContainer.onclick = ({target: target_Bt}) =>
{
if (!target_Bt.matches('button[data-op]')) return
// console.clear()
// console.log( target_Bt.dataset.op, target_Bt.dataset.ref )
if (target_Bt.dataset.op==='readed')
{
// things to do with target_Bt.dataset.ref
}
if (target_Bt.dataset.op==='remove')
{
// things to do with target_Bt.dataset.ref
// let idx = books.findIndex(({id})=>id=== +target_Bt.dataset.ref)
target_Bt
.closest('div.booksDisplay')
.querySelector('div.imageContainer')
.classList.add('BookRemove');
}
}
.booksContainer {
font-family : Arial, Helvetica, sans-serif;
font-size : 14px;
}
.imageContainer {
width : 80px;
height : 30px;
background : aquamarine;
}
.textContainer button {
margin : 0 0 2.4em 1em;
}
.imageContainer.BookRemove {
border : 1px solid rgb(107, 107, 107);
}
.noDisplay {
display: none;
}
form[name="add-New-Book"] {
margin-bottom : 2em;
width : 20em;
}
form input {
margin-bottom : .4em;
width : 19em;
}
form fieldset {
padding-bottom : 0;
margin-bottom : .4em;
}
form[name="add-New-Book"] input:read-only {
background-color: lightblue;
}
button[name="btConfirm"] {
width : 10em;
background-color : #7bff00;
border-radius : 4px;
}
button[name="btCancel"] {
width : 5em;
background-color : #ebb222;
border-radius : 4px;
}
.as-console-row::after {display: none !important;}
.as-console-row-code {background: yellow;}
<form name="add-New-Book">
<fieldset>
<legend> new Book </legend>
<input type="text" name="titles" placeholder="Title" required>
<input type="text" name="author" placeholder="Author" required>
<input type="number" name="pages" placeholder="Number of pages" required min="0">
<input type="link" name="imageUrl" placeholder="Image URL" required>
</fieldset>
<button type="button" name="btAdd"> Add a new book </button>
<button type="button" name="btConfirm" class="noDisplay"> Confirm </button>
<button type="button" name="btCancel" class="noDisplay"> Cancel </button>
<button type="reset">reset</button>
</form>
<div class="booksContainer">
Okay, I figured it out. It seems like I have to add an ID to the whole object(It was 4 before and I changed it to ID: 1. Then I added return {...newBook, author: inputAuthor.value, title: inputTitle.value, pages: inputPages.value} in a new array.
I currently have some code which takes an array of javascript objects and generates an html list based on it, I want to display the corresponding image with the text in the list. But currently I can only get it to display the address if the image of text. Any help would be appreciated thanks!
HTML
<form>
<p>Please insert the items</p>
<input type="text" id="box" />
</form>
<div id="root"></div>
CSS
ul {
border: 2px solid grey;
border-radius: 5px;
padding: 1em;
}
li {
display: inline-block;
padding: 0.5em;
}
JS
const catalog = {
GalaxyTablet: {
name: "GalaxyTablet",
key: "galaxytablet",
keywords: ["galaxy", "tablet", "samsung"],
price: 800,
image: "https://www.jbhifi.co.nz/FileLibrary/ProductResources/Images/150044-M-HI.jpg"
},
GalaxyPhone: {
name: "GalaxyPhone",
key: "galaxyphone",
keywords: ["galaxy", "phone", "samsung"],
price: 1000,
image: "https://assets.kogan.com/files/product/etail/Samsung-/S10WHT_03.jpg?auto=webp&canvas=753%2C502&fit=bounds&height=502&quality=75&width=753"
},
HTCPhone: {
name: "HTCPhone",
key: "htcphone",
keywords: ["htc", "phone"],
price: 650,
image: "https://cdn.mos.cms.futurecdn.net/ca063713e185be46e62ec2eb3762a540.jpg"
},
};
const form = document.querySelector("form");
form.addEventListener("submit", submitHandler);
function submitHandler(event) {
event.preventDefault();
const searchTerm = form.box.value;
const results = search(searchTerm);
render(results);
}
function search(searchTerm) {
return Object.keys(catalog)
.filter((key) => catalog[key].keywords.includes(searchTerm.toLowerCase()))
.map((key) => catalog[key]);
}
function render(results) {
const root = document.querySelector("#root");
const list = results.map(itemToLi).join("");
root.innerHTML = `<ul>
${list}
</ul>`;
}
function itemToLi(item) {
return `<li>${item.name}</li>$ ${item.price}<li> <li>${item.image}<li>`;
}
You're only getting the URI text because that is what you are outputting:
<li>${item.image}<li>
You need to create an img tag:
<li><img src="${item.image}"></li>
Here's a small demo with the contents of your catalog:
const catalog = {
GalaxyTablet: {
name: "GalaxyTablet",
key: "galaxytablet",
keywords: ["galaxy", "tablet", "samsung"],
price: 800,
image: "https://www.jbhifi.co.nz/FileLibrary/ProductResources/Images/150044-M-HI.jpg"
},
GalaxyPhone: {
name: "GalaxyPhone",
key: "galaxyphone",
keywords: ["galaxy", "phone", "samsung"],
price: 1000,
image: "https://assets.kogan.com/files/product/etail/Samsung-/S10WHT_03.jpg?auto=webp&canvas=753%2C502&fit=bounds&height=502&quality=75&width=753"
},
HTCPhone: {
name: "HTCPhone",
key: "htcphone",
keywords: ["htc", "phone"],
price: 650,
image: "https://cdn.mos.cms.futurecdn.net/ca063713e185be46e62ec2eb3762a540.jpg"
}
};
const root = document.querySelector("#root");
const list = Object.values(catalog).map(itemToLi).join("");
root.innerHTML = `<ul>
${list}
</ul>`;
function itemToLi(item) {
return `<li>${item.name}</li>$ <li>${item.price}</li> <li><img src="${item.image}"></li>`;
}
<div id="root"></div>
You need to use img tag to render image. Also do not forget to use alt attribute inside that.
You can update your existing JavaScript method itemToLi as :
function itemToLi(item) {
return `<li>${item.name}</li>$ <li>${item.price}</li> <li><img src="${item.image}" alt=">${item.name}"></li>`;
}
I want to preload my images and rotate them every 3 seconds.
I'm having trouble with the rotate and preload functions. I need to preload my images when the page first loads and rotate them every 3 seconds. I've tried having the images in an array and not in an array. Nothing seems to work.
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Index Page</title>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<!-- JavaScript files -->
<script src="js/preloadImages.js" type="text/javascript"></script>
<script src="js/rotateImages.js" type="text/javascript"></script>
</head>
<body>
<div class "centered">
<img src="images/banner1.jpg" id="idBanner" alt="idBanner">
</div>
</body>
</html>
//JAVASCRIPT CODE//
window.onload=loadImage;
var images = [];
function loadImage(){
for (var i=0; i < arguments.length; i++){
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
preload(
"images/banner1.jpg", "images/banner2.jpg", "images/banner3.jpg", "images/silhouette.jpg", "images/work.jpg", "images/firefighter.jpg", "images/event.jpg")
window.onload=rotate;
var count=0;
var bannerImages = new Array("images/banner1.jpg", "images/banner2.jpg", "images/banner3.jpg");
function rotate(){
count++;
if (count==bannerImages.length){
count = 0;
}
document.getElementById("idBanner").src = bannerImages[count];
setTimeOut(rotate, 3*1000);
}
a way to go...
const ImgLoad = [ { img: null, src: 'images/banner1.jpg' }
, { img: null, src: 'images/banner2.jpg' }
, { img: null, src: 'images/banner3.jpg' }
, { img: null, src: 'images/silhouette.jpg' }
, { img: null, src: 'images/work.jpg' }
, { img: null, src: 'images/firefighter.jpg'}
, { img: null, src: 'images/event.jpg' }
]
, ImgBann = [ 'images/banner1.jpg', 'images/banner2.jpg', 'images/banner3.jpg' ]
, ImgRota = document.getElementById("idBanner")
var ItemBann = 0
for (let ref of ImgLoad)
{
ref.img = new Image()
ref.img.src = ref.src
}
setInterval(() =>
{
ItemBann = ++ItemBann % ImgBann.length
ImgRota.src = ImgBann[ItemBann]
}
, 3000)
you can also use: (to make sure all images are fully loaded before any "rotation")
const ImgLoad = [ { img: null, src: 'images/banner1.jpg' }
, { img: null, src: 'images/banner2.jpg' }
, { img: null, src: 'images/banner3.jpg' }
, { img: null, src: 'images/silhouette.jpg' }
, { img: null, src: 'images/work.jpg' }
, { img: null, src: 'images/firefighter.jpg'}
, { img: null, src: 'images/event.jpg' }
]
, ImgBann = [ 'images/banner1.jpg'
, 'images/banner2.jpg'
, 'images/banner3.jpg'
]
, ImgRota = document.getElementById("idBanner")
var ItemBann = 0
, ImgLoaded = 0
for (let ref of ImgLoad)
{
ref.img = new Image()
ref.img.onload = () =>{ ImgLoaded++ }
ref.img.src = ref.src
}
setInterval(() =>
{
if (ImgLoaded === ImgLoad.length )
{
ItemBann = ++ItemBann % ImgBann.length
ImgRota.src = ImgBann[ItemBann]
}
}
, 3000)
Now, I have tow buttons. The first button named "array1", the other button named 'array2'. I have an array called "newArray." I have an array named "array1". I have an array named "array2".I have an array called "unselectedArray."
When I click the array1 button, I want to show the item in array1, but the item is not in "newArray1". When I click the array2 button, I want to show the item in array2, but the item is not in "newArray1" This show array is "unselectedArray."
When I click the item in the "unselectedArray," the item is added in 'newArrray';
I use two hours to solve it, but I haven't written the right code.
This is my code:
<style>
.bigDiv {
width: 500px; height: 100%;
margin: 60px auto; background-color: red;
}
li {
float: left;
width: 50px; height: 50px;
}
.selected,.buttonArea,.unselected {
height: 100px;
}
</style>
<div class="bigDiv">
<div class="selected">
<ul>
<li ng-repeat="item in newArray">
{{item.text}}
</li>
</ul>
</div>
<div class="buttonArea">
<button ng-click="showArrayFun('array1')">array1</button>
<button ng-click="showArrayFun('array2')">array2</button>
</div>
<div class="unselected">
<ul>
<li ng-click="addToNewArrayFun($index)" ng-repeat="item in unselectedArray">
{{item.text}}
</li>
</ul>
</div>
</div>
angular.module('myApp', []).controller('con', function ($scope) {
$scope.array1 = [
{
id: 11,
text: 'one'
},
{
id: 12,
text: 'two'
},
];
$scope.array2 = [
{
id: 21,
text: 'winter'
},
{
id: 22,
text: 'spring'
},
];
$scope.newArray = [
{
id: 12,
text: 'two'
}
];
$scope.unselectedArray = [];
$scope.addToNewArrayFun = function (index) {
$scope.newArray.push($scope.unselectedArray[index]);
};
$scope.showArrayFun = function (arrayName) {
if (arrayName == 'array1') {
$scope.unselectedArray = $scope.array1.filter(function (item) {
console.log(($scope.newArray.indexOf(item) == -1));
return ( ($scope.newArray.indexOf(item) == -1) == true );
});
} else if (arrayName == 'array2') {
$scope.unselectedArray = $scope.array2.filter(function (item) {
console.log(($scope.newArray.indexOf(item) == -1));
return ( ($scope.newArray.indexOf(item) == -1) == true );
});
}
}
}
);
Why my code not work? Who can correct my code?
Please write the code which is using $filter.
Who can create AngularJS custom filters to realize it.
// Code goes here
angular.module('myApp', []).controller('con', function ($scope) {
$scope.array1 = [
{
id: 11,
text: 'one'
},
{
id: 12,
text: 'two'
},
];
$scope.array2 = [
{
id: 21,
text: 'winter'
},
{
id: 22,
text: 'spring'
},
];
$scope.newArray = [
{
id: 12,
text: 'two'
}
];
$scope.unselectedArray = [];
$scope.addToNewArrayFun = function (index) {
$scope.newArray.push($scope.unselectedArray[index]);
$scope.unselectedArray.splice(index, 1);
};
$scope.showArrayFun = function (arrayName) {
if (arrayName == 'array1') {
$scope.unselectedArray = $scope.array1.filter(function (item) {
return ( ($scope.newArray.indexOf(item) == -1));
});
} else if (arrayName == 'array2') {
$scope.unselectedArray = $scope.array2.filter(function (item) {
return ( ($scope.newArray.indexOf(item) == -1));
});
}
};
})
/* Styles go here */
.bigDiv {
width: 500px; height: 100%;
margin: 60px auto;
background-color: red;
}
li {
float: left;
width: 50px; height: 50px;
}
.selected,.buttonArea,.unselected {
height: 100px;
}
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body ng-controller="con">
<div class="bigDiv">
<div class="selected">
<ul>
<li ng-repeat="item in newArray">
{{item.text}}
</li>
</ul>
</div>
<div class="buttonArea">
<button ng-click="showArrayFun('array1')">array1</button>
<button ng-click="showArrayFun('array2')">array2</button>
</div>
<div class="unselected">
<ul>
<li ng-click="addToNewArrayFun($index)" ng-repeat="item in unselectedArray">
{{item.text}}
</li>
</ul>
</div>
</div>
</body>
</html>
<div class="bigDiv">
<div class="selected">
<ul>
<li ng-click=" deleteItemFun($index)" ng-repeat="item in newArray track by $index ">
{{item.text}}
</li>
</ul>
</div>
<div class="buttonArea">
<button ng-click="showArrayFun('array1')">array1</button>
<button ng-click="showArrayFun('array2')">array2</button>
</div>
<div class="unselected">
<ul>
<li ng-click="addToNewArrayFun($index)" ng-repeat="item in unselectedArray | fiArray : newArray ">
{{item.text}}
</li>
</ul>
</div>
</div>
angular.module('myApp', []).filter('fiArray', function () {
return function (array, aimArray) {
var tempArray = array;
if (tempArray.length == 0)
return [];
for (var i = 0; i < aimArray.length; i++) {
for (var j = 0; j < tempArray.length; j++) {
if (tempArray[j].id === aimArray[i].id) {
tempArray.splice(j, 1);
j--;
break;
}
}
}
return tempArray;
}
})
.controller('con', ['$scope', 'fiArrayFilter', function ($scope, fiArrayFilter) {
$scope.newArray = [
{
id: 12,
text: 'two'
}
];
$scope.array1 = [
{
id: 11,
text: 'one'
},
{
id: 12,
text: 'two'
},
];
$scope.array2 = [
{
id: 21,
text: 'winter'
},
{
id: 22,
text: 'spring'
},
];
$scope.unselectedArray = [];
$scope.addToNewArrayFun = function (index) {
$scope.newArray.push($scope.unselectedArray[index]);
};
$scope.deleteItemFun = function (index) {
$scope.newArray.splice(index, 1)
}
$scope.showArrayFun = function (arrayName) {
var copyArr = [];
if (arrayName == 'array1') {
copyArr = $scope.array1.concat();
}
else if (arrayName == 'array2') {
copyArr = $scope.array2.concat();
}
$scope.unselectedArray = copyArr;
}
}])
;