how to add dynamically multiple posts with jsonplaceholder - arrays

help me please, I display the html markup of 6 posts, the first click works correctly, the second click I display the same posts. how should I add six new posts, and so every time I click?
I don't know what can be used instead of the slice method. demo https://jsfiddle.net/u9zc7p5v/13/
const content = mrd.map(function(data, elem) {
return `
<div class="blog__item">
<h2 class="blog__item-title">
${data.title}
</h2>
<input type="checkbox" class="read-more-state" id="post-${elem}" />
<p class="blog__item-text">
${data.body} <span class="blog__item-more">Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem itaque ducimus unde harum vitae quam provident. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta sapiente odit laborum tempore sed quaerat a aliquam? Corrupti dolorum, tempora iste qui modi consectetur explicabo quia vel reiciendis nesciunt? Id!</span>
</p>
<label for="post-${elem}" class="blog__item-toggle" >Read More</label>
<div>${elem}</div>
</div>
`
}).slice(startNum, endNum).join('');

Increase the startNum value startNum+=6. then in slice function do startNum + endNum.
$(function(){
const blogs = document.querySelector('.blog__items')
const moreBtn = document.querySelector('.blog-btn')
let startNum = 0;
let endNum = 6;
async function getContent() {
let responce = await fetch('https://jsonplaceholder.typicode.com/posts');
let data = await responce.json();
return data;
}
$(moreBtn).on('click', async function(e) {
let mrd = await getContent();
console.log(mrd.length)
const content = mrd.map(function(data, elem) {
return `
<div class="blog__item">
<h2 class="blog__item-title">
${data.title}
</h2>
<p class="blog__item-text">
${data.body} <span class="blog__item-more">Lorem ipsum dolor sit amet consectetur adipisicing elit. Autem itaque ducimus unde harum vitae quam provident. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dicta sapiente odit laborum tempore sed quaerat a aliquam? Corrupti dolorum, tempora iste qui modi consectetur explicabo quia vel reiciendis nesciunt? Id!</span>
</p>
<label class="blog__item-toggle" >Read More</label>
<div>${elem}</div>
</div>
`
}).slice(startNum, startNum+endNum).join('');
console.log(startNum)
const el = $(content);
$(blogs).append(el)
el.on('click', function() {
});
startNum+= 6
});
});

Related

How to post to json sever

tried posting to json db but only gets the Id in the json server with no postdate, posttitle, postdesc and image. i dont know i am doing wrong.
I would also like to like to update a post and then should be redirected to the homepage after updating the post.
I had tried using Redirect, useHistory and then useNavigate ffrom react-router-dom but still isnt working
import { useEffect, useState } from "react";
import "./write.css";
import { useNavigate } from "react-router-dom";
export default function Write() {
const [image, setImage] = useState();
const [posttitle, setPostTitle] = useState("");
const [postdesc, setPostDesc] = useState("");
const [postdate, setPostDate] = useState("20/30/2020");
// const [postDate, setPostDate] = useState("");
const navigate = useNavigate();
//==============================================================//
//Publishing or posting a post to the json server
const formSubmit = (e)=> {
e.preventDefault();
const docs = {
image,
posttitle,
postdate,
postdesc,
};
fetch("http://localhost:8005/posts", {
method: "POST",
headers: { contentType: "application/json" },
body: JSON.stringify(docs),
}).then(() => {
navigate.push("/home");
});
console.log(docs);
}
//===============================================================//
// const { id } = useParams(); not working
// getting the id of the post to be edited using window.location.href
const url = window.location.href;
const id = url.substring(url.lastIndexOf("=") + 1);
// //editing/Updating post data in the json-server file
// function editBtn() {
// fetch("http://localhost:8005/posts/" + id, {
// method: "PUT",
// body: JSON.stringify(),
// headers: {
// contentType: "application.json",
// },
// });
// }
return (
<div className="write">
<form className="writeform" onSubmit={formSubmit}>
<div>
<input />
date here
</div>
<div className="image_container">
{image && (
<div>
<img
className="writeimage"
alt="postimage"
src={URL.createObjectURL(image)}
onChange={(e) => {
setImage(e.target.src);
}}
/>
</div>
)}
</div>
<div className="writeformgroup">
<label htmlFor="fileinput">
<i className="writeicon fa-solid fa-plus"></i>
</label>
<input
id="fileinput"
type="file"
onChange={(e) => {
setImage(e.target.files[0]);
}}
style={{ display: "none" }}
/>
<input
type="text"
// value={postTitle}
className="writeinput"
onChange={(e) => {
setPostTitle(e.target.value);
}}
autoFocus
/>
</div>
<div className="writeformgroup">
<textarea
// value={postDesc}
onChange={(e) => {
setPostDesc(e.target.value);
}}
type="text"
className="writeinput writetext"
></textarea>
</div>
<button className="writesubmit">Publish</button>
</form>
<p>{posttitle}</p>
</div>
);
}
//JSON DB
{
"posts": [
{
"image": "https://images.pexels.com/photos/9968415/pexels-photo-9968415.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"posttitle": "Lorem ipsum dolor sit amet ",
"postdate": "20-29-2022",
"postdesc": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur sequi ad eveniet necessitatibus reiciendis dolor deleniti qui mod",
"id": 1
},
{
"image": "https://images.pexels.com/photos/13957041/pexels-photo-13957041.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"posttitle": "Lorem ipsum dolor sit amet ",
"postdate": "20-29-2022",
"postdesc": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur sequi ad eveniet necessitatibus reiciendis dolor deleniti qui mod",
"id": 2
},
{
"image": "https://images.pexels.com/photos/13715795/pexels-photo-13715795.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"posttitle": "Lorem ipsum dolor sit amet ",
"postdate": "20-29-2022",
"postdesc": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur sequi ad eveniet necessitatibus reiciendis dolor deleniti qui mod",
"id": 3
},
{
"image": "https://images.pexels.com/photos/13420447/pexels-photo-13420447.jpeg?auto=compress&cs=tinysrgb&w=400&lazy=load",
"posttitle": "Lorem ipsum dolor sit amet ",
"postdate": "20-29-2022",
"postdesc": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur sequi ad eveniet necessitatibus reiciendis dolor deleniti qui mod",
"id": 4
},
{
"image": "https://images.pexels.com/photos/13950829/pexels-photo-13950829.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"posttitle": "Lorem ipsum dolor sit amet ",
"postdate": "20-29-2022",
"postdesc": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur sequi ad eveniet necessitatibus reiciendis dolor deleniti qui mod",
"id": 5
},
{
"image": "https://images.pexels.com/photos/11055161/pexels-photo-11055161.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
"posttitle": "Lorem ipsum dolor sit amet ",
"postdate": "20-29-2022",
"postdesc": "Lorem ipsum dolor sit amet consectetur adipisicing elit. Saepe, suscipit inventore. Facilis ducimus quod ratione, fugiat temporibus, porro vitae consequuntur aspernatur sequi ad eveniet necessitatibus reiciendis dolor deleniti qui mod",
"id": 6
}
]
}
Try useHistory for redirect issues
import { useHistory } from 'react-router-dom';
const histroy = useHistory();
histroy.push({ pathname: '/home' });
Try async /await for fetch
const formSubmit = async () => {
try{
const response = await fetch("http://localhost:8005/posts", {
method: "POST",
headers: { contentType: "application/json" },
body: JSON.stringify(docs),
});
if(!response || !response.ok){
throw new Error('error message');
}
const data = response.json();
console.log(data);
}catch(error){
console.log(error);
}
}

How to apply CSS animations to React components that re-render

I am attempting to reproduce the sliding image effect seen on this website https://chiwawa.es/en/.
I can see how it works on this website (see changeImages function in 63c2acc.js; however, getting this to work in React is proving difficult for me.
To illustrate what I have managed to do, I've published https://dskdirhhwk.vercel.app/.
Solved - (this link now correctly shows animations thanks to answer below)
The difficulty I'm running into is animating the images. The Sections are getting re-rendered by React upon state update, affecting how I apply the classes to the markup. I used Reacts Profiler to verify these are updates, not remounts.
I initially had the Intersection Observer outside the Section component, but this didn't appear to work. I also had a simple setState mechanism and have since built it into a reducer, so that I could add the active class after the other classes.
I am pulling my hair out here. I want a few hints and a push in the right direction!
This is on Next.js. Here is my code.
import React, {
Fragment,
useState,
forwardRef,
useEffect,
useLayoutEffect,
useCallback,
useContext,
useRef,
useMemo,
} from 'react';
import cx from 'classnames';
// yarn add classnames
const useIntersect = ({root = null, rootMargin, threshold = 0}) => {
const [entry, updateEntry] = useState({});
const [node, setNode] = useState(null);
const observer = useRef(null);
useEffect(() => {
if (observer.current) observer.current.disconnect();
observer.current = new IntersectionObserver(([entry]) => updateEntry(entry), {
root,
rootMargin,
threshold,
});
const {current: currentObserver} = observer;
if (node) currentObserver.observe(node);
return () => currentObserver.disconnect();
}, [node]);
return [setNode, entry];
};
const Home = () => {
const initialState = {active: 'teal', current: 'teal'};
const [state, dispatch] = React.useReducer(reducer, initialState);
function reducer(state, {section, type}) {
switch (type) {
case 'reset':
return initialState;
case 'changeSection':
return {
...state,
previous: state?.current,
current: section,
};
case 'makeActive':
return {
...state,
active: section,
};
default:
return state;
}
}
const activeSection = (section) => {
dispatch({section: section, type: 'changeSection'});
setTimeout(() => {
dispatch({type: 'makeActive', section: section});
}, 1000);
};
const Section = ({sectionID, className, children}) => {
const [ref, entry] = useIntersect({
threshold: '0.7',
});
useEffect(() => {
if (state?.current == sectionID) return;
if (entry.isIntersecting) {
activeSection(sectionID);
}
}, [entry]);
const childrenWithProps = React.Children.map(children, (child, index) => {
if (React.isValidElement(child)) {
if (index == 0)
return React.cloneElement(child, {
className: cx(
'fixed top-0 w-1/2 h-screen transition-all duration-[1000ms] place-items-center place-content-center transform-gpu',
{
'translate-y-[-100vh]': sectionID != state?.active,
'z-40 translate-y-0': sectionID == state?.current && sectionID == state?.active,
}
),
data: 'observable',
id: sectionID,
});
}
return child;
});
return (
<section className={className} ref={ref}>
{childrenWithProps}
</section>
);
};
return (
<>
<div className="fixed bottom-0 z-50 w-1/2 opacity-50">
<pre>{JSON.stringify(state, null, 2)}</pre>
</div>
<Section sectionID="teal" className="bg-teal-200">
<div>
<img className="block object-cover w-full h-full" src="http://placekitten.com/800/1600?image=1" />
</div>
<div className="flex flex-col justify-center w-1/2 min-h-screen px-8 py-64 ml-auto section_content">
<p className="mb-6">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent mollis molestie eros eget
ultricies. Mauris tempus odio fermentum, elementum odio a, molestie metus. Nullam id dolor
viverra, scelerisque mi nec, volutpat sapien. Aenean ac nibh gravida, congue velit sit amet,
ultricies mi. Ut posuere ullamcorper elit, eget faucibus turpis fermentum mattis. Nulla
facilisi. Aliquam volutpat maximus vehicula. Nulla commodo dolor vitae euismod condimentum.
Maecenas et justo rutrum, varius velit at, facilisis mauris. Maecenas eget eros in dui mollis
tempor iaculis eu massa. Nulla ullamcorper finibus cursus.
</p>
</div>
</Section>
<Section sectionID="blue" className="bg-blue-200">
<div>
<img className="block object-cover w-full h-full" src="http://placekitten.com/800/1600?image=2" />
</div>
<div className="flex flex-col justify-center w-1/2 min-h-screen px-8 py-64 ml-auto section_content">
<p className="mb-6">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent mollis molestie eros eget
ultricies. Mauris tempus odio fermentum, elementum odio a, molestie metus. Nullam id dolor
viverra, scelerisque mi nec, volutpat sapien. Aenean ac nibh gravida, congue velit sit amet,
ultricies mi. Ut posuere ullamcorper elit, eget faucibus turpis fermentum mattis. Nulla
facilisi. Aliquam volutpat maximus vehicula. Nulla commodo dolor vitae euismod condimentum.
Maecenas et justo rutrum, varius velit at, facilisis mauris. Maecenas eget eros in dui mollis
tempor iaculis eu massa. Nulla ullamcorper finibus cursus.
</p>
</div>
</Section>
<Section sectionID="orange" className="bg-orange-200">
<div>
<img className="block object-cover w-full h-full" src="http://placekitten.com/800/1600?image=3" />
</div>
<div className="flex flex-col justify-center w-1/2 min-h-screen px-8 py-64 ml-auto section_content">
<p className="mb-6">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent mollis molestie eros eget
ultricies. Mauris tempus odio fermentum, elementum odio a, molestie metus. Nullam id dolor
viverra, scelerisque mi nec, volutpat sapien. Aenean ac nibh gravida, congue velit sit amet,
ultricies mi. Ut posuere ullamcorper elit, eget faucibus turpis fermentum mattis. Nulla
facilisi. Aliquam volutpat maximus vehicula. Nulla commodo dolor vitae euismod condimentum.
Maecenas et justo rutrum, varius velit at, facilisis mauris. Maecenas eget eros in dui mollis
tempor iaculis eu massa. Nulla ullamcorper finibus cursus.
</p>
</div>
</Section>
<Section sectionID="pink" className="bg-pink-200">
<div>
<img className="block object-cover w-full h-full" src="http://placekitten.com/800/1600?image=4" />
</div>
<div className="flex flex-col justify-center w-1/2 min-h-screen px-8 py-64 ml-auto section_content">
<p className="mb-6">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent mollis molestie eros eget
ultricies. Mauris tempus odio fermentum, elementum odio a, molestie metus. Nullam id dolor
viverra, scelerisque mi nec, volutpat sapien. Aenean ac nibh gravida, congue velit sit amet,
ultricies mi. Ut posuere ullamcorper elit, eget faucibus turpis fermentum mattis. Nulla
facilisi. Aliquam volutpat maximus vehicula. Nulla commodo dolor vitae euismod condimentum.
Maecenas et justo rutrum, varius velit at, facilisis mauris. Maecenas eget eros in dui mollis
tempor iaculis eu massa. Nulla ullamcorper finibus cursus.
</p>
</div>
</Section>
</>
);
};
export default Home;
You should (almost) never ever ever declare a component inside of another functional component. Doing so essentially creates an entirely new React component class every render, which means it is impossible for React to reconcile which component is which between renders. Try moving your <Section> functional component definition out of the scope of <Home>.

Stack columns if browser size is small

I have 2 columns on my page... my issue is that I want the right column to stack underneath my left column if browser size is made smaller. I am using angular material but don't mind using custom styling to fix this. Any help will be appreciated.
HTML:
<div layout="row" layout-align="center center" flex>
<section layout="row">
<div id="nav" flex="20" layout="column" layout-align="space-around">
<md-calendar class="fixed-calendar" ng-model="myDate"></md-calendar>
</div>
<div id="content" flex>
<h2>Right Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
</div>
</section>
</div>
CSS:
.datepickerdemoBasicUsage md-content {
padding-bottom: 200px; }
.datepickerdemoBasicUsage .validation-messages {
font-size: 11px;
color: darkred;
margin: 10px 0 0 25px; }
.fixed-calendar {
width: 340px;
height: 340px;
display: block;
}
.fixed-calendar .md-calendar-scroll-mask {
width: 340px !important;
}
.fixed-calendar .md-virtual-repeat-scroller {
width: 340px !important;
height: 308px;
overflow: hidden !important;
}
JSFiddle Demo
Something like this on your parent layout="column" layout-gt-xs="row"
<div ng-app="sandbox">
<div>
<section layout="column" layout-gt-xs="row">
<div id="nav" flex>
<md-calendar class="fixed-calendar" ng-model="myDate"></md-calendar>
</div>
<div id="content" flex>
<h2>Right Column</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas maxime officia aliquam nesciunt debitis quam optio odio soluta corrupti, mollitia, possimus iure quos nostrum eius nam. Aperiam voluptatum voluptate unde.</p>
</div>
</section>
</div>
</div>
This says stack child elements into a column.
Then if the browser width gets to greater than or equal xs (>= 600px), make child elements into a row.
Fiddle

angular collapseAll not working

I have used bootstrap plugin to collapse and expand the <div>s. I am able to do it for individual <div>'s but if i leave one <div> expanded and do a collapseAll(), the expanded <div> only getting collapsed. Please provide me a solution on this
html:
<body ng-controller="MainCtrl">
<div class="panel panel-default" ng-repeat="item in items">
<div class="panel-heading" ng-click="isCollapsed = !isCollapsed">{{item.title}}</div>
<div class="panel-body" collapse="isCollapsed">{{item.content}}</div>
</div>
<div>
<input type="checkbox" id="collapse_all_cards" ng-model="isCollapsed"><label for="collapse_all_cards">Collapse All</label>
</div>
</body>
js:
var app = angular.module('plunker', ['ui.bootstrap']);
app.controller('MainCtrl', function($scope) {
$scope.items = [{'title':'Item1','content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus maximus orci sodales, pellentesque urna eu'},
{'title':'Item2','content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus maximus orci sodales, pellentesque urna eu'},
{'title':'Item3','content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus maximus orci sodales, pellentesque urna eu'}
]
});
link: http://plnkr.co/edit/mcnqeLJcTyaAuTI9JHb9
Please see this Plunk
Pretty sure this is the behavour you are after :)
The problem before was that the same "isCollapsed" property on scope was being used for the "collapse all" and the individual collapses so they were tripping each other up.
See the new controller code which has an individual boolean "isCollapsed" property for each item in the collection:
{'title':'Item1','content':'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus maximus orci sodales, pellentesque urna eu', isCollapsed: true}
If you need any refinements to the code just ask :)

Selecting an 'object' logic

I have done this before but I can't for the life of me remember how. I want a user to be able to select a product by clicking a button in an <li> then have that passed to an array. As well as that, the <li> needs to have a class 'active' once that item is in the selected array:
<li class="row" data-ng-repeat="product in products">
<div class="col-lg-9">
<h3>{{product.name}}</h3>
<p>{{product.description}}</p>
</div>
<div class="col-lg-3">
<button class="btn btn-primary" data-ng-click="selectProduct(product.id)">Select Product</button>
</div>
</li>
is the HTML and this is the controller:
app.controller("MainController", function($scope, $http) {
$scope.selected_products = []
$scope.products = [
{
name: 'Example product',
description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, assumenda, dolor, ipsa, atque obcaecati tempora perspiciatis earum vitae amet cum nostrum blanditiis ducimus culpa molestiae temporibus porro debitis voluptatibus libero.',
category: 'VT'
},
{
name: 'Example product 2',
description: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id, assumenda, dolor, ipsa, atque obcaecati tempora perspiciatis earum vitae amet cum nostrum blanditiis ducimus culpa molestiae temporibus porro debitis voluptatibus libero.',
category: 'VT'
}
]
$scope.selectProduct = function(name) {
console.log(name)
}
})
Does anyone have any pointers as to how to do this?
Here you are:
$scope.isSelected = function(product){
return this.selected_products.indexOf(product)>-1;
}
$scope.selectProduct = function(product) {
if(!this.isSelected(product)){
this.selected_products.push(product);
}
}
Use it like:
<button ng-disabled="isSelected(product)" data-ng-click="selectProduct(product)">Select Product</button>
Working example: http://plnkr.co/edit/sPAN36?p=preview

Resources