AngularJS access Data from Resource Query - javascript

I have a Jersey Rest Application which I d'like to access with a AngularJS application.
I have defined the resource as follows:
Service:
angular.service('Wine', function ($resource) {
return $resource('/myserver/rest/wines/:wineId', {}, {
update: {method:'PUT'},
'query': {method: 'GET', isArray: true}
});
});
Controller:
function WineListCtrl(Wine) {
this.wines = Wine.query();
}
In Firebug I can see the result of this GET-Request:
{"wine":[{"country":"USA","description":"With hints of ginger and spice, this wine makes an excellent complement to light appetizer and dessert fare for a holiday gathering.","grapes":"Pinot Noir","id":"9","name":"BLOCK NINE","picture":"block_nine.jpg","region":"California","year":"2009"},{"country":"Argentina","description":"Solid notes of black currant blended with a light citrus make this wine an easy pour for varied palates.","grapes":"Pinot Gris","id":"11","name":"BODEGA LURTON","picture":"bodega_lurton.jpg","region":"Mendoza","year":"2011"},{"country":"France","description":"The aromas of fruit and spice give one a hint of the light drinkability of this lovely wine, which makes an excellent complement to fish dishes.","grapes":"Grenache / Syrah","id":"1","name":"CHATEAU DE SAINT COSME","picture":"saint_cosme.jpg","region":"Southern Rhone / Gigondas","year":"2009"},{"country":"France","description":"Though dense and chewy, this wine does not overpower with its finely balanced depth and structure. It is a truly luxurious experience for the\nsenses.","grapes":"Merlot","id":"7","name":"CHATEAU LE DOYENNE","picture":"le_doyenne.jpg","region":"Bordeaux","year":"2005"},{"country":"France","description":"The light golden color of this wine belies the bright flavor it holds. A true summer wine, it begs for a picnic lunch in a sun-soaked vineyard.","grapes":"Merlot","id":"8","name":"DOMAINE DU BOUSCAT","picture":"bouscat.jpg","region":"Bordeaux","year":"2009"},{"country":"USA","description":"Though subtle in its complexities, this wine is sure to please a wide range of enthusiasts. Notes of pomegranate will delight as the nutty finish completes the picture of a fine sipping experience.","grapes":"Pinot Noir","id":"10","name":"DOMAINE SERENE","picture":"domaine_serene.jpg","region":"Oregon","year":"2007"},{"country":"Spain","description":"A resurgence of interest in boutique vineyards has opened the door for this excellent foray into the dessert wine market. Light and bouncy, with a hint of black truffle, this wine will not fail to tickle the taste buds.","grapes":"Tempranillo","id":"2","name":"LAN RIOJA CRIANZA","picture":"lan_rioja.jpg","region":"Rioja","year":"2006"},{"country":"France","description":"Breaking the mold of the classics, this offering will surprise and undoubtedly get tongues wagging with the hints of coffee and tobacco in\nperfect alignment with more traditional notes. Breaking the mold of the classics, this offering will surprise and\nundoubtedly get tongues wagging with the hints of coffee and tobacco in\nperfect alignment with more traditional notes. Sure to please the late-night crowd with the slight jolt of adrenaline it brings.","grapes":"Chardonnay","id":"12","name":"LES MORIZOTTES","picture":"morizottes.jpg","region":"Burgundy","year":"2009"},{"country":"USA","description":"The cache of a fine Cabernet in ones wine cellar can now be replaced with a childishly playful wine bubbling over with tempting tastes of\nblack cherry and licorice. This is a taste sure to transport you back in time.","grapes":"Sauvignon Blanc","id":"3","name":"MARGERUM SYBARITE","picture":"margerum.jpg","region":"California Central Cosat","year":"2010"},{"country":"USA","description":"A one-two punch of black pepper and jalapeno will send your senses reeling, as the orange essence snaps you back to reality. Don't miss\nthis award-winning taste sensation.","grapes":"Syrah","id":"4","name":"OWEN ROE \"EX UMBRIS\"","picture":"ex_umbris.jpg","region":"Washington","year":"2009"},{"country":"USA","description":"One cannot doubt that this will be the wine served at the Hollywood award shows, because it has undeniable star power. Be the first to catch\nthe debut that everyone will be talking about tomorrow.","grapes":"Pinot Noir","id":"5","name":"REX HILL","picture":"rex_hill.jpg","region":"Oregon","year":"2009"},{"country":"Italy","description":"Though soft and rounded in texture, the body of this wine is full and rich and oh-so-appealing. This delivery is even more impressive when one takes note of the tender tannins that leave the taste buds wholly satisfied.","grapes":"Sangiovese Merlot","id":"6","name":"VITICCIO CLASSICO RISERVA","picture":"viticcio.jpg","region":"Tuscany","year":"2007"}]}
In my html page I d'like to access the content as following:
<ul ng:controller="WineListCtrl">
<li ng:repeat="wine in wines">
<a href='#/wines/{{ wine.id }}'>{{ wine.name }}</a>
</li>
</ul>
Sadly there are no results showing up in the UI (although the JSON Result seems to be okay and there is no error on the Browser Console).
If I make an alert like
alert(this.wines.length)
I get 0 as result.
Would be great to get some help of you guys...
Greets
Marc

Your first problem is that you're assigning to this and not the scope. If you don't assign to the scope, your data won't be available for binding in the view. So inject the $scope into your controller and assign it the wines attribute:
function WineListCtrl($scope, Wine) {
$scope.wines = Wine.query();
}
You have another problem though. The ngResource module expects the result of call to query to be an array, but you're actually returning an object:
{wine: [an array of wines]}
So unless you remove the key from the server-side response, your ng-repeat might have to look something like:
<li ng-repeat="wine in wines.wine">...</li>

Related

Unable to Clear 'Search' results

I am looking to clear Search results when a new query is entered in the websites search bar.
For example I am developing a TV search website, if I search 'Friends' a list of results will display however if I enter a new query the results will not clear and print at the bottom of the previous list of results.
I have tried features such as resultList.innerHTML = '';
Here is some of my JavaScript:
fetch(`https: //api.tvmaze.com/search/shows?q=${TVShow}`)
.then((response) => response.json())
.then((data) => {
for (const value of data) {
document.querySelector(".TVShowInfo").insertAdjacentHTML('beforeend',
`<div id="TVShow">
<center>
<h1>${value.show.name}</h1>
</center>
</div>`);
}
})
<div class="searchBox">
<input id="TVShowName" type="TV show information" placeholder="Search for a TV show..." />
<button id="search">Search</button>
</div>
<div class="TVShowInfo"></div>
Try this - just replace the innerHTML instead of insertAdjacentHTML.
I also changed the ID to class and removed the deprecated center
document.querySelector(".TVShowInfo").innerHTML = data
.map(({show}) => `<div class="TVShow"><h1>${show.name}</h1></div>`).join('<br/>');
.TVShow { text-align: center; }
<div class="TVShowInfo"></div>
<script>
const data = [{"score":0.9089527,"show":{"id":431,"url":"https://www.tvmaze.com/shows/431/friends","name":"Friends","type":"Scripted","language":"English","genres":["Comedy","Romance"],"status":"Ended","runtime":30,"averageRuntime":30,"premiered":"1994-09-22","ended":"2004-05-06","officialSite":null,"schedule":{"time":"20:00","days":["Thursday"]},"rating":{"average":8.5},"weight":98,"network":{"id":1,"name":"NBC","country":{"name":"United States","code":"US","timezone":"America/New_York"},"officialSite":"https://www.nbc.com/"},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":3616,"thetvdb":79168,"imdb":"tt0108778"},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/41/104550.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/41/104550.jpg"},"summary":"<p>Six young (20-something) people from New York City (Manhattan), on their own and struggling to survive in the real world, find the companionship, comfort and support they get from each other to be the perfect antidote to the pressures of life.</p><p>This average group of buddies goes through massive mayhem, family trouble, past and future romances, fights, laughs, tears and surprises as they learn what it really means to be a friend.</p>","updated":1641068842,"_links":{"self":{"href":"https://api.tvmaze.com/shows/431"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/40881"}}}},{"score":0.8193341,"show":{"id":46948,"url":"https://www.tvmaze.com/shows/46948/friends","name":"Friends","type":"Scripted","language":"English","genres":["Drama","Comedy"],"status":"Ended","runtime":60,"averageRuntime":60,"premiered":"1979-03-25","ended":"1979-04-22","officialSite":null,"schedule":{"time":"","days":["Sunday"]},"rating":{"average":null},"weight":21,"network":{"id":3,"name":"ABC","country":{"name":"United States","code":"US","timezone":"America/New_York"},"officialSite":"https://"+"abc.com/"},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":null,"thetvdb":76973,"imdb":"tt0078615"},"image":null,"summary":"A comedy-drama series as seen through the eyes of three 11-year-old children from different backgrounds with episodes focusing upon the trials and tribulations of adolescence, and involved subjects such as dating, family, school, growing pains and friendship.","updated":1585366201,"_links":{"self":{"href":"https://api.tvmaze.com/shows/46948"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/1824845"}}}},{"score":0.8159303,"show":{"id":30774,"url":"https://www.tvmaze.com/shows/30774/friends","name":"Friends","type":"Scripted","language":"Japanese","genres":["Drama","Romance"],"status":"Ended","runtime":65,"averageRuntime":65,"premiered":"2002-02-04","ended":"2002-02-05","officialSite":"http://www.tbs.co.jp/friends21/","schedule":{"time":"21:00","days":["Monday","Tuesday"]},"rating":{"average":null},"weight":19,"network":{"id":159,"name":"TBS","country":{"name":"Japan","code":"JP","timezone":"Asia/Tokyo"},"officialSite":"https://www.tbs.co.jp/"},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":null,"thetvdb":99721,"imdb":"tt0315608"},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/122/305714.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/122/305714.jpg"},"summary":"<p>Left alone on a trip to Hong Kong, Tomoko finds herself the victim of a purse-snatching. The police arrest the man she points out, but it turns out to be the wrong person: a young Korean man named Ji Hoon. Despite his anger and humiliation, he takes her out to dinner since she has lost all her money, and in return, she agrees to model for his amateur film. What follows is a magical and romantic two days. Upon returning to their respective countries, Tomoko must return to her nine-to-five job and Ji Hoon must resume studying to join the family business rather than pursuing his dream of becoming a film director. But soon the two begin to email each other and rekindle their relationship despite the distance and obstacles between them. Marking the very first time in television history that a drama has been co-produced between Japan and South Korea, the story shows us that love has no borders.</p>","updated":1635779876,"_links":{"self":{"href":"https://api.tvmaze.com/shows/30774"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/1260315"}}}},{"score":0.807294,"show":{"id":53703,"url":"https://www.tvmaze.com/shows/53703/friends","name":"Friends","type":"Variety","language":"Korean","genres":[],"status":"Ended","runtime":90,"averageRuntime":90,"premiered":"2021-02-17","ended":"2021-05-12","officialSite":"http://m.ichannela.com/program/menu/prm_menu2_mob.do?pgm_contents=050078&type=02&menuIndex=2&seqIndex=0&realCateCode=05007801&boardType=null&boardId=null&cateName=%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%A8%20%EC%86%8C%EA%B0%9C","schedule":{"time":"21:10","days":["Wednesday"]},"rating":{"average":null},"weight":16,"network":{"id":538,"name":"Channel A","country":{"name":"Korea, Republic of","code":"KR","timezone":"Asia/Seoul"},"officialSite":null},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":null,"thetvdb":396947,"imdb":null},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/297/743857.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/297/743857.jpg"},"summary":"<p>Reuniting old friends and introducing new acquaintances, cast members from Heart Signal 2 & 3 are back in a brand new variety series and sparks are sure to fly! Invited to spend a very special winter at Signal House, relationships between Oh Young Joo, Jung Jae Ho, Kim Do Gyun, Kim Jang Mi, Lee Ga Heun, Park Ji Hyun, Seo Min Jae, and Jung Eui Dong are sure to blossom. But which relationships will remain friendly and which will blossom into love? Follow the members through their daily lives and find out! Hosted by Super Junior's Kim Hee Chul and Shindong, Oh My Girl's Seunghee, and Lee Sang Min.</p>","updated":1668808710,"_links":{"self":{"href":"https://api.tvmaze.com/shows/53703"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/2090402"}}}},{"score":0.69863015,"show":{"id":47182,"url":"https://www.tvmaze.com/shows/47182/smiling-friends","name":"Smiling Friends","type":"Animation","language":"English","genres":["Comedy"],"status":"Running","runtime":15,"averageRuntime":15,"premiered":"2020-04-01","ended":null,"officialSite":"http://www.adultswim.com/videos/smiling-friends","schedule":{"time":"","days":["Sunday"]},"rating":{"average":null},"weight":91,"network":{"id":10,"name":"Adult Swim","country":{"name":"United States","code":"US","timezone":"America/New_York"},"officialSite":null},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":null,"thetvdb":379403,"imdb":"tt12074628"},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/251/628722.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/251/628722.jpg"},"summary":"<p>A small company dedicated to bringing happiness to the world receives a simple request to help a woman's unhappy son smile again, but the job turns out to be more complicated than it seems.</p>","updated":1659887321,"_links":{"self":{"href":"https://api.tvmaze.com/shows/47182"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/2365336"}}}},{"score":0.6878882,"show":{"id":20474,"url":"https://www.tvmaze.com/shows/20474/angels-friends","name":"Angel's Friends","type":"Animation","language":"Italian","genres":["Adventure","Children","Fantasy"],"status":"Ended","runtime":15,"averageRuntime":15,"premiered":"2009-10-12","ended":"2012-04-29","officialSite":"http://www.angelsfriends.it","schedule":{"time":"","days":["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]},"rating":{"average":null},"weight":69,"network":{"id":1272,"name":"Italia 1","country":{"name":"Italy","code":"IT","timezone":"Europe/Rome"},"officialSite":null},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":null,"thetvdb":264933,"imdb":"tt1731708"},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/72/180985.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/72/180985.jpg"},"summary":"<p>Special school for the Angels is full of secrets! What happens if at the same table will be angels and devils? Raf, Uri, Sweet and Mickey - a company of angels. But to become a real team, they do not have a single person. Friends leave their homes and go down to the Earth in the \"Golden School\". They need to get the last \"missing percentage\", which will make their guardian angels at 100%. Their mission is to accompany selected earthlings in their daily adventures...</p>","updated":1573079445,"_links":{"self":{"href":"https://api.tvmaze.com/shows/20474"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/1382408"}}}},{"score":0.68657506,"show":{"id":65357,"url":"https://www.tvmaze.com/shows/65357/only-friends","name":"Only Friends","type":"Scripted","language":"Thai","genres":["Drama","Romance"],"status":"In Development","runtime":null,"averageRuntime":null,"premiered":null,"ended":null,"officialSite":"https://www.gmm-tv.com/home/","schedule":{"time":"","days":[]},"rating":{"average":null},"weight":66,"network":{"id":1095,"name":"GMM25","country":{"name":"Thailand","code":"TH","timezone":"Asia/Bangkok"},"officialSite":null},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":null,"thetvdb":null,"imdb":null},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/431/1079406.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/431/1079406.jpg"},"summary":null,"updated":1669158203,"_links":{"self":{"href":"https://api.tvmaze.com/shows/65357"}}}},{"score":0.6837748,"show":{"id":11090,"url":"https://www.tvmaze.com/shows/11090/mutual-friends","name":"Mutual Friends","type":"Scripted","language":"English","genres":["Drama","Comedy"],"status":"Ended","runtime":60,"averageRuntime":60,"premiered":"2008-08-26","ended":"2008-09-30","officialSite":"http://www.bbc.co.uk/programmes/b00d98sz","schedule":{"time":"21:00","days":["Tuesday"]},"rating":{"average":null},"weight":65,"network":{"id":12,"name":"BBC One","country":{"name":"United Kingdom","code":"GB","timezone":"Europe/London"},"officialSite":"https://www.bbc.co.uk/bbcone"},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":18729,"thetvdb":82899,"imdb":"tt1062325"},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/37/93077.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/37/93077.jpg"},"summary":"<p>Martin has two best friends, Patrick and Carl, who couldn't be more different. One is an irresponsible, unreliable, feckless womaniser and the other is dead. Guess which one slept with his wife?Martin Grantham is happily married to Jen. They have a son Dan, a nice house, the works. One day his best friend Carl throws himself under a train, setting off a disastrous sequence of events that will change Martin's life forever…Into this mess steps Patrick, a friend from way back. Patrick is everything Martin is not – glib, self-confident, popular and pathologically immature. He's the last person Martin needs in his life right now. Or is he?</p>","updated":1555974558,"_links":{"self":{"href":"https://api.tvmaze.com/shows/11090"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/555093"}}}},{"score":0.68103445,"show":{"id":7403,"url":"https://www.tvmaze.com/shows/7403/battlefield-friends","name":"Battlefield Friends","type":"Animation","language":"English","genres":["Comedy","Adventure"],"status":"Ended","runtime":3,"averageRuntime":3,"premiered":"2012-03-20","ended":"2016-08-20","officialSite":"https://www.youtube.com/show/battlefieldfriends","schedule":{"time":"","days":[]},"rating":{"average":null},"weight":56,"network":null,"webChannel":{"id":21,"name":"YouTube","country":null,"officialSite":"https://www.youtube.com"},"dvdCountry":null,"externals":{"tvrage":null,"thetvdb":262928,"imdb":"tt2354667"},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/27/68210.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/27/68210.jpg"},"summary":"<p><b>Battlefield Friends</b> is a series of animated shorts set in the game world of Battlefield 3 and Battlefield 4. It chronicles the misadventures of four friends and squadmembers, embodying the four soldier classes available in the games. The series often comically attacks/parodies player trends and game mechanics, such as spawnkilling, buggy bipods, Closet Colonels, etc.</p><p>The series follows four players-a medic, an engineer, a sniper, and a noob. The series incorporates surreal humor mixed with cartoon comedy gags.</p>","updated":1657875759,"_links":{"self":{"href":"https://api.tvmaze.com/shows/7403"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/903483"}}}},{"score":0.6768293,"show":{"id":45922,"url":"https://www.tvmaze.com/shows/45922/graceful-friends","name":"Graceful Friends","type":"Scripted","language":"Korean","genres":["Drama","Crime","Mystery"],"status":"Ended","runtime":80,"averageRuntime":80,"premiered":"2020-07-10","ended":"2020-09-05","officialSite":"http://tv.jtbc.joins.com/gracefulfriends","schedule":{"time":"22:50","days":["Friday","Saturday"]},"rating":{"average":null},"weight":55,"network":{"id":268,"name":"jTBC","country":{"name":"Korea, Republic of","code":"KR","timezone":"Asia/Seoul"},"officialSite":null},"webChannel":null,"dvdCountry":null,"externals":{"tvrage":null,"thetvdb":378806,"imdb":"tt12531492"},"image":{"medium":"https://static.tvmaze.com/uploads/images/medium_portrait/262/655331.jpg","original":"https://static.tvmaze.com/uploads/images/original_untouched/262/655331.jpg"},"summary":"<p><b>Graceful Friends</b> is a mystery drama about a murder that occurs in a new town inhabited by married couples in their 40s and follows the story of a group of middle-aged men after their peaceful everyday lives are disrupted.</p>","updated":1655183561,"_links":{"self":{"href":"https://api.tvmaze.com/shows/45922"},"previousepisode":{"href":"https://api.tvmaze.com/episodes/1914740"}}}}]
</script>
just set the innerHtml to blank
<body>
<div class="searchBox">
<input id="TVShowName" type="search" placeholder="Search for a TV show..." />
<button id="search">Search</button>
</div>
<div class="TVShowInfo"></div>
</div>
</div>
<script>
const searchInput = document.getElementById("TVShowName");
const contentArea = document.querySelector(".TVShowInfo");
function searchShow(TVShow) {
fetch(`https://api.tvmaze.com/search/shows?q=${TVShow}`)
.then((response) => response.json())
.then((data) => {
contentArea.innerHTML = "";
for (const value of data) {
contentArea.insertAdjacentHTML(
"beforeend",
`
<div id="TVShow">
<center>
<h1>${value.show.name}</h1>
</center>
</div>`
);
// searchInput.value = "";
}
});
}
document.getElementById("search").onclick = function (e) {
searchShow(searchInput.value);
};
</script>
</body>

How to use innerHTML in my code to align the text in the center?

I am trying to make a website using html, css and js which shows jokes when refreshed. I can display my jokes using document.write() but I dont know how to center align it so it would look good. I searched the web and found that we could use inner.HTML function but I cant understand how to use it in my code. Pls help.
My code-
Js code-
let jokes = [`I just got my doctor's test results and I'm really upset about it. Turns out, I'm not gonna be a doctor.`,
`My grief counselor died. He was so good, I don’t even care.`,
` Today, I asked my phone “Siri, why am I still single?” and it activated the front camera.`,
` A man wakes from a coma. His wife changes out of her black clothes and, irritated, remarks, “I really cannot depend on you in anything, can I!”`,
` As I get older, I remember all the people I lost along the way. Maybe my budding career as a tour guide was not the right choice.`,
` I was digging in our garden and found a chest full of gold coins. I wanted to run straight home to tell my wife about it. Then I remembered why I was digging in our garden.`,
` The doctor gave me some cream for my skin rash. He said I was a sight for psoriasis.`,
` Don’t challenge Death to a pillow fight. Unless you’re prepared for the reaper cushions.`,
` I don’t have a carbon footprint. I just drive everywhere.`,
` Even people who are good for nothing have the capacity to bring a smile to your face, like when you push them down the stairs.`,
` A man walks into an enchanted forest and tries to cut down a talking tree. "You can't cut me down," the tree exclaims, "I'm a talking tree!" The man responds, "You may be a talking tree, but you will dialogue."`,
` My mom died when we couldn’t remember her blood type. As she died, she kept telling us to “be positive,” but it’s hard without her.`,
` What does my dad have in common with Nemo? They both can’t be found.`,
` I visited my new friend in his apartment. He told me to make myself at home. So I threw him out. I hate having visitors.`,
` When my Uncle Frank died, he wanted his cremations to be buried in his favorite beer mug. His last wish was to be Frank in Stein.`,
` Do you know the phrase “One man’s trash is another man’s treasure”? Wonderful saying, horrible way to find out that you were adopted.`,
` My husband left a note on the fridge that said, "This isn't working." I'm not sure what he's talking about. I opened the fridge door and it's working fine!`,
` Why did the man miss the funeral? He wasn’t a mourning person.`,
` It’s important to establish a good vocabulary. If I had known the difference between the words “antidote” and “anecdote,” one of my best friends would still be alive.`,
` Want to know how you make any salad into a caesar salad? Stab it twenty-three times.`,
` When I see the names of lovers engraved on a tree, I don't find it cute or romantic. I find it weird how many people take knives with them on outings.`,
` Give a man a match, and he’ll be warm for a few hours. Set him on fire, and he will be warm for the rest of his life.`,
` My wife is mad that I have no sense of direction. So I packed up my stuff and right.`,
` When does a joke become a dad joke? When it leaves you and never comes back.`,
` A priest asks the convicted murderer at the electric chair, “Do you have any last requests?” “Yes,” replies the murderer. “Can you please hold my hand?”`,
` I just read that someone in New York gets stabbed every 52 seconds. Poor guy.`,
` The doctor gave me one year to live, so I shot him with my gun. The judge gave me 15 years. Problem solved.`,
` You know you’re not liked when you get handed the camera every time they take a group photo.`,
` Where did Joe go after getting lost on a minefield? Everywhere.`,
` What's red and bad for your teeth? A brick.`,
` My grandfather said my generation relies too much on the latest technology. So I unplugged his life support.`,
` My parents raised me as an only child, which really pissed off my sister.`,
` What did the Titanic say as it sank? I’m nominating all passengers for the Ice Bucket Challenge!`,
` Why did Mozart kill all of his chickens? When he asked them who the best composer was, they all replied, "Bach, Bach, Bach."`,
` How many emo kids does it take to screw in a lightbulb? None, they all sit in the dark and cry.`,
` I have a stepladder because my real ladder left when I was `,
` They laughed at my crayon drawing. I laughed at their chalk outline.`,
` My husband and I have reached the difficult decision that we do not want children. If anybody does, please just send me your contact details and we can drop them off tomorrow.`,
` I have many jokes about unemployed people, sadly none of them work.`,
` The most corrupt CEOs are the ones who run pretzel companies. They’re always so twisted.`,
` To teach kids about democracy, I let them vote on dinner. They picked tacos. Then I made pizza because they don’t live in a swing state.`,
` I was reading a great book about an immortal cat the other day. It was impossible to put down.`,
` You’re not completely useless. You can always be used as a bad example.`,
` I threw a boomerang a few years ago. I now live in constant fear.`,
`What’s the difference between a hipster and a football player? A football player showers.`,
` I made a website for orphans. It doesn’t have a home page.`,
` The other day, my girlfriend asked me to pass her lipstick but I accidentally passed her a glue stick. She still isn't talking to me.`,
` Why can’t Michael Jackson go within 500 meters of a school? Because he’s dead.`,
` “I’m sorry” and “I apologize” mean the same thing. Except at a funeral.`,
` It turns out a major new study recently found that humans eat more bananas than monkeys. But, I can’t remember the last time I ate a monkey.`,
` Never break someone's heart, they only have one of those. Break their bones instead, they have 206 of them.`,
` What’s the difference between a Lamborghini and a dead body? I don’t have a Lamborghini in my garage.`,
` When ordering food at a new restaurant, my wife asked the waiter what they do to prepare their chicken.“Nothing special,” he explained. “We just tell them they’re going to die.”`,
` What is the difference between Iron man and Iron Woman? One is a superhero and the other is a simple command.`,
` I'll never forget my Grandfather’s last words to me just before he died. "Are you still holding the ladder?"`,
` Sorry, what’s the quickest way to get to the hospital? Easy, just stand in the middle of a busy road.`,
` Why don’t cannibals eat clowns? Because they taste funny.`,
` What’s the hardest part of a vegetable to eat? The wheelchair.`,
` What's the difference between jelly and jam? You can't jelly a clown into the tiny car.`,
` My grandma has the heart of a lion and a lifetime ban from the zoo.`,
` What do you call inexpensive circumcision? A rip-off.`,
` What did the woman with no hands get for Christmas? No idea. She hasn’t opened her present yet.`,
` "I work with animals," the guy says to his Tinder date. "That's so sweet," she replies. "I like a man who loves animals. Where do you work?" "I'm a butcher," he says.`,
` What’s the difference between a baby and a sweet potato? About 140 calories.`,
` You don’t need a parachute to go skydiving. You need a parachute to go skydiving twice.`,
` Today was the worst day of my life. My ex got hit by a school bus, and I lost my job as a bus driver.`,
` Why was the leper hockey game canceled? It was because of a face-off in the corner.`,
` They say the surest way to a man’s heart is through the stomach. But, I find going through the ribcage a lot easier.`,
` What's the last thing to go through a fly's head as it hits the windshield of a car going 80 mph? Its butt.`,
` What’s the special dish in a restaurant for cannibals? Heads, shoulders, knees, and toes`,
` Why are friends a lot like snow? If you pee on them, they disappear.`,
` What do you call a dog with no legs? Doesn’t matter what you call him, he won’t come anyway.`,
` An apple a day keeps the doctor away. Or at least it does if you throw it hard enough.`,
` Why is it that if you donate a kidney, people love you. But if you donate five kidneys, they call the police.`,
` My senior relatives liked to tease me at weddings, saying things like, “You’ll be next!” They stopped once I started doing the same to them at funerals.`,
` Happy 60th birthday. At last, you can live undisturbed by life insurance agents!`,
` Imagine if you walked into a bar and there was a long line of people waiting to hit you. That's the punch line.`,
`Dark humor is like food. Not everyone gets it.`,
`The cemetery is so crowded. People are just dying to get in.`,
`I was drinking a martini and the waitress screamed “does anyone know CPR?” I yelled, “I know the entire alphabet” and we all laughed and laughed. Well, except one person.`,
`I know a fish that can breakdance! Only for 20 seconds though, and only once.`,
`I childproofed my house. Somehow they still got in!`,
`Why don’t skeletons ever go trick or treating? Because they have no body to go with.`,
`Cremation. My final hope for a smokin’ hot body!`,
`Today on a drive, I decided to go visit my childhood home. I asked the people living there if I could come inside because I was feeling nostalgic, but they refused and slammed the door in my face. My parents are the worst.`,
`People with Covid have no taste!`,
`My favorite Disney movie is The Hunchback of Notre Dame. I love a hero with a twisted back story.`,
`My girlfriend wanted a marriage just like a fairy tale. Fair enough. I gave her a loaf of bread and left her in the forest.`,
`I heard Sony is coming out with a new video game console to help us get through the pandemic. It's called the Plaguestation`,
`I’ve stopped making jokes about Covid to my brother. They flu over his head.`,
`My boss told me to have a good day. So I went home.`,
`I got a job at a library, but it only lasted 15 minutes. Turns out, books about women’s rights shouldn’t go in the Sci-Fi / Fantasy section.`,
`I started crying when dad was cutting onions. Onions was such a good dog.`,
`My daughter asked me how stars die. "Usually an overdose," I told her.`,
`What do you call it when every one of your friends makes too many dumb Covid jokes? A pundemic.`,
`What did Kermit the Frog say at his puppeteer’s funeral? Not a word.`,
`Why is there air conditioning in hospitals? To keep the vegetables cool and fresh.`,
`The guy who stole my diary just died. My thoughts are with his family.`,
`Since the pandemic started, my husband just stands there sadly looking through the window. I should probably go let him inside.`,
`I was shocked when I found out my toaster was not waterproof.`]
let item = jokes[Math.floor(Math.random() * jokes.length)];
let a = document.getElementById
document.write(item)
HTML code-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Jokes</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>
Best jokes collection
</h1>
<div id="first"><i>Wanna hear a joke</i></div>
<div id="second">Refresh for more</div>
<script src="script.js"></script>
<script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script>
</body>
</html>
CSS code-
h1{
color: red;
text-align: center;
font-size: 60px;
}
#first{font-size: 40px;
font-weight: 20px;
text-align: center;
font-style: italic;
}
#second{
margin: 100px;
text-align: center;
font-size: 20px;
}
#second a{
text-decoration: none;
}
Try this:
https://jsfiddle.net/16t73qhe/
Add a <p class="joke"></p>
Then set the joke text into it document.querySelector('p.joke').textContent = item
Ensure the CSS centres the joke p.joke { text-align: center;}
However, there are many better ways of achieving this, but keep learning!

show less or show more in javaScript html [duplicate]

This question already has answers here:
HTML - How to make a "Read More" button
(3 answers)
Closed 1 year ago.
I have a code like this. I want to show maxlength 100 but when I click button I want to see all text. When I click button again I want to show length is going to be 100 again.
I didn't do it. Can you help me ?
Sorry for my English
function MyButton () {
var x = document.getElementById("p1").maxLength = 300;
document.querySelector('.p1').innerText = x;
$("#More").css("display", "none")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="p1" >
Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined
</span>
<button onclick="MyButton()" id="More">..Show More</button>
You can do a little trick like this where you assign the full text content to a dataset attribute at page load but display the short version on the page.
When the button is clicked, assign the short text content to another dataset attribute and display the full text. This process then repeats to hide the full text when the button is clicked again.
document.querySelectorAll('button.More').forEach(bttn=>{
bttn.dataset.state=0;
bttn.addEventListener('click',function(e){
let span=this.previousElementSibling;
span.dataset.tmp=span.textContent;
span.textContent=span.dataset.content;
span.dataset.content=span.dataset.tmp;
this.innerHTML=this.dataset.state==1 ? 'Show More...' : 'Show Less...';
this.dataset.state=1-this.dataset.state;
})
});
document.querySelectorAll('span.p1').forEach(span=>{
span.dataset.content=span.textContent;
span.textContent=span.textContent.substr(0,100) + '...';
})
.p1{margin:1rem;display:block;}
<span class="p1" >
Breaking India: Western Interventions in Dravidian and Dalit Faultlines is a book written by Rajiv Malhotra and Aravindan Neelakandan which argues that India's integrity is being undermined
</span>
<button class="More">..Show More</button>
<span class="p1" >
I hate yogurt. It's just stuff with bits in. You hit me with a cricket bat. All I've got to do is pass as an ordinary human being. Simple. What could possibly go wrong? I'm the Doctor, I'm worse than everyone's aunt. *catches himself* And that is not how I'm introducing myself.
All I've got to do is pass as an ordinary human being. Simple. What could possibly go wrong? The way I see it, every life is a pile of good things and bad things.…hey.…the good things don't always soften the bad things; but vice-versa the bad things don't necessarily spoil the good things and make them unimportant.
</span>
<button class="More">..Show More</button>
<span class="p1" >
Saving the world with meals on wheels. Saving the world with meals on wheels. It's art! A statement on modern society, 'Oh Ain't Modern Society Awful?'! I'm nobody's taxi service; I'm not gonna be there to catch you every time you feel like jumping out of a spaceship.
You hit me with a cricket bat. You've swallowed a planet! You know how I sometimes have really brilliant ideas? Heh-haa! Super squeaky bum time! Aw, you're all Mr. Grumpy Face today.
</span>
<button class="More">..Show More</button>
<span class="p1" >
Aw, you're all Mr. Grumpy Face today. I am the last of my species, and I know how that weighs on the heart so don't lie to me! All I've got to do is pass as an ordinary human being. Simple. What could possibly go wrong?
You hit me with a cricket bat. No, I'll fix it. I'm good at fixing rot. Call me the Rotmeister. No, I'm the Doctor. Don't call me the Rotmeister. Stop talking, brain thinking. Hush. I am the last of my species, and I know how that weighs on the heart so don't lie to me!
</span>
<button class="More">..Show More</button>

Wrap a set of paragraphs with no markup and random <br> in p tags

I'm working on themes for a legacy API that spits out less than wonderful / if not markup-less / markup. I've been able to wrestle most of it back into shape with wrap() and other methods, but for some reason this one is stumping me. Do I really need to get out the for loops for something like this - or is there a cheap and dirty way to get these paragraphs into <p> paragraphs?
<div class="bio">
"Some Ember is the new solo project of Man/Miracle's Dylan Travis. "Era of Wind" is only the second song he's released, it is icy and desolate. It's a little bit Lovecraft (From fingertip to dilated eye/ it closes grip on vibrated flesh, Travis sings) and a little bit Fever Ray, propelled by haunted, droning bass. I keep thinking about this lonely guy in a lake, like a 19th century convict rowing through fog, making his great escape from an island prison and sinking halfway to shore. What happens to that guy? What if he had a Moog to play on the way down? " --The Fader
<br>
<br>
"Like some kind of abridged soundtrack to Bergman's Persona pared down to its abstract purity, this ten minute mood piece charts a psychic journey through dissolution and restructure, opening with a searing purge of the sonic palate, only to find itself wading through the aftermath's fog of disarray. Taking cues from the likes of Mazzy Star, Happy New Year and Grouper, the San Francisco duo immerse themselves in a narcotic mixture of sensuality and obliqueness, mostly leaving meaning and catharsis to hover just out of reach while an ominous air of gloom takes hold." --Sonic Masala
</div>
Feels like trying to get these in shape might not be worth it. Thoughts?
Maybe you can achieve this using the childNodes in DOM .
$("#btnConvert").on("click",function(){
var text = $("#text");
result = $("<div>").html(text.val()).children().contents().filter(function() {
return this.nodeType == 3 && this.data.trim() != "";
}).map(function(){ return "<p>"+this.data+"</p>"}).get().join("");
text.val(result);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<p>value</p>
<textarea name="text" id="text" cols="30" rows="10">
<div class="bio">
"Some Ember is the new solo project of Man/Miracle's Dylan Travis. "Era of Wind" is only the second song he's released, it is icy and desolate. It's a little bit Lovecraft (From fingertip to dilated eye/ it closes grip on vibrated flesh, Travis sings) and a little bit Fever Ray, propelled by haunted, droning bass. I keep thinking about this lonely guy in a lake, like a 19th century convict rowing through fog, making his great escape from an island prison and sinking halfway to shore. What happens to that guy? What if he had a Moog to play on the way down? " --The Fader
<br>
<br>
"Like some kind of abridged soundtrack to Bergman's Persona pared down to its abstract purity, this ten minute mood piece charts a psychic journey through dissolution and restructure, opening with a searing purge of the sonic palate, only to find itself wading through the aftermath's fog of disarray. Taking cues from the likes of Mazzy Star, Happy New Year and Grouper, the San Francisco duo immerse themselves in a narcotic mixture of sensuality and obliqueness, mostly leaving meaning and catharsis to hover just out of reach while an ominous air of gloom takes hold." --Sonic Masala
</div>
</textarea>
<br>
<input type="button" id="btnConvert" name="btnConvert" value="Convert">
You should look into Regex if you're going to be doing a lot of this. You get much more control over your text and the code is short.
I called .match on the innerHTML and using this regex string /".+/g. It finds all text from the left-most quote until a newline.
text.match(/".+/g);
Here's how the match parses out.
https://regex101.com/r/mP7pU9/1
This is how it looks in jQuery.
http://jsfiddle.net/jg7cxpy4/2/

How can I pass data between controllers in AngularJS?

I need to keep two separate controllers, one for a search area and one to display data. When a search is performed I need to fetch data from the internet and update the view with the new data. I don't want to wrap everything with a bigger controller or something like that (is this best practice?) but I'd prefer the search and display controllers to remain completely separate.
This is the html code relative to the search field and display grid
<div id="mainContainer" class="container-fluid" >
<div id="searchContainer">
<div id="search" ng-controller="SearchController as srcCtrl">
<!-- on submit call submit(title) -->
<form class="navbar-form" role="search">
<div class="input-group">
<input ng-model="title" type="text" class="form-control" placeholder="Search" name="srch-term" id="srch-term">
<div class="input-group-btn">
<button class="btn btn-default" ng-click="srcCtrl(title)"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
</div>
</div>
<div id="animeContainer" class="container-fluid">
<div class="clearfix"></div>
<!-- animeContainer directive -->
<anime-container></anime-container>
</div>
</div>
And the Angular code:
(function(){
var app = angular.module('hummingbird', []);
app.controller('AnimeListController', function(){
this.anime = animeList; //list of anime to display in anime list
this.onSelectAnime = function(anime){
console.log(anime);
};
});
app.controller('SearchController', function(){
this.submit = function(srcstr){
//here I call the API and then I want to update the anime variable in AnimeListController
console.log(srcstr);
}
});
app.directive("animeContainer", function(){
return{
restrict: 'E',
templateUrl: 'anime-container.html',
}
});
var animeList = [{"id":25,"slug":"ghost-in-the-shell","status":"Finished Airing","url":"https://hummingbird.me/anime/ghost-in-the-shell","title":"Ghost in the Shell","alternate_title":null,"episode_count":1,"cover_image":"https://static.hummingbird.me/anime/poster_images/000/000/025/large/25.jpg?1408440508","synopsis":"In the year 2029, the barriers of our world have been broken down by the net and by cybernetics, but this brings new vulnerability to humans in the form of brain-hacking. When a highly-wanted hacker known as 'The Puppetmaster' begins involving them in politics, Section 9, a group of cybernetically enhanced cops, are called in to investigate and stop the Puppetmaster. The pursuit will call into question what makes a human and what is the Puppetmaster in a world where the distinction between human and machine is increasingly blurry.\n(Source: ANN)","show_type":"Movie"},{"id":1411,"slug":"ghost-hunt","status":"Finished Airing","url":"https://hummingbird.me/anime/ghost-hunt","title":"Ghost Hunt","alternate_title":"","episode_count":25,"cover_image":"https://static.hummingbird.me/anime/poster_images/000/001/411/large/1411.jpg?1408443952","synopsis":"Telling ghost stories is a favorite past time of Mai Taniyama and her friends—that is, until she meets 17-year-old Kazuya Shibuya, the man sent by Shibuya Psychic Research Center to investigate paranormal activity at a supposedly haunted school. When Mai gets caught in a dangerous situation, she is rescued by Kazuya's assistant. Saving her lands the assistant incapacitated, and Kazuya demands that Mai become his assistant, instead. (Source: ANN)","show_type":"TV"},{"id":4135,"slug":"seven-ghost","status":"Finished Airing","url":"https://hummingbird.me/anime/seven-ghost","title":"07-Ghost","alternate_title":"","episode_count":25,"cover_image":"https://static.hummingbird.me/anime/poster_images/000/004/135/large/4135.jpg?1408451649","synopsis":"Set in a gothic fantasy world, this is the story of Teito Klein, an orphaned slave who became the top military academy student. However, an unexpected turn of events left him pursued by the forces of the Barsburg Empire. Now an escaping convict, Teito's sheltered by the church and its law of sanctuary. Here, he discovered many mysteries surrounding himself, the church, and the Empire itself. The fact that he might be connected to a dethroned king and the mystical stone of god, \"The Eye of Mikhael\", made him the target of the empire more than ever. Fortunately the church is under the mythical 7 Ghost protection. But who are the Ghosts really. Will Teito be free from the military's clutch, and what of his said mission to uncover the history. And who is the military's Chief-of-Staff Ayanami exactly. Teito's future seems to have spiraled into an unexpectedly perilous path.\r\n[Source: ANN]","show_type":"TV"},{"id":6391,"slug":"ghost-messenger","status":"Currently Airing","url":"https://hummingbird.me/anime/ghost-messenger","title":"Ghost Messenger","alternate_title":null,"episode_count":6,"cover_image":"https://static.hummingbird.me/anime/poster_images/000/006/391/large/6391.jpg?1408458272","synopsis":"Ghost Messengers are super-power agents from the underground world called the World of Death. The World of Death is a digitalized world with cutting-edge technologies that control and manage the life and death of all living things based on its elaborate systems.\r\nOur Ghost Messenger hero, Kang-lim, has been dispatched to the human world to capture the remaining ghosts who are refusing to go to the World of Death although it is their time.\r\nAn accident occurs during his mission and Kang-lim gets captured in his own mobile phone. Little Kang-lim, a human boy who has extraordinary spiritual powers, finds the mobile phone and takes GhostMessenger Kang-lim out from the mobile phone.\r\nAnd the adventure begins.\r\n(Source: Anime World Network)","show_type":"OVA"},{"id":2360,"slug":"shinreigari-ghost-hound","status":"Finished Airing","url":"https://hummingbird.me/anime/shinreigari-ghost-hound","title":"Shinreigari: Ghost Hound","alternate_title":null,"episode_count":22,"cover_image":"https://static.hummingbird.me/anime/poster_images/000/002/360/large/2360.jpg?1408446509","synopsis":"In an isolated region of Kyushu lies the town of Suiten. Though seeming small and modest, Suiten is not a picturesque place for a vacation, unless it is from the “Unseen Worldâ€. Taro, Makoto and Masayuki, three boys with traumatic pasts, learn to let their souls cross between the two parallel worlds. However, the Unseen World is no mere copy of the real Apparent World. The Unseen World is the home of ghosts, but changes are now allowing the souls of the dead to pass over into the Apparent World, with unpredictable effects. Follow the journey of Taro, Makoto and Masayuki, as they cross between the two worlds, trying to unravel a great mystery. \n(Source: Sentai Filmworks)","show_type":"TV"}];
})();
anime-container-html
<div class="col-md-3 col-xs-6" ng-repeat="anime in animeListCtrl.anime">
<!-- anime in anime list-->
<div class="panel panel-default fixed-height highlight" ng-click="animeListCtrl.onSelectAnime(anime)">
<div class="panel-body">
<img class="img-rounded img-responsive center-block" ng-src="{{anime.cover_image}}"/>
<h3> {{anime.title}} </h3>
</div>
</div>
</div>
I'm sure there's a pretty simple solution but I only find something that seems using old versions of AngularJS (I'm using 1.2.26).
Thanks everybody!
P.S. any other tip or advice about best practices are welcome!
What you want to do is add a service that you can then inject into your other controllers/directives. In your example, I imagine something like SearchService would work. In your submit function, rather than invoking the API directly have it call into the SearchService to execute the search. The SearchService would then maintain and expose the result set. Any controller and/or directive interested in displaying the results could bind to SearchService.resultSet, for instance.
Remember that Angular services are singleton objects. So if you intend on having more than a single search form/result object you may need to enhance your service to store named searches. However, based on the code you've shown, it looks like a single resultset would suffice. You could, optionally, decorate the ctrl,directive,service as part of an anime-specific module. So instead of SearchService call it AnimeSearchService.
app.factory('AnimeSearchService', function($http) {
var service = { resultSet: {} };
service.executeSearch = function(args) {
... some API calls ...
// when they return results store them as service.resultSet
}
return service;
});
Then in your controller
app.controller('AnimeSearchController', function(AnimeSearchService){
this.submit = function(srcstr){
//here I call the API and then I want to update the anime variable in AnimeListController
AnimeSearchService.executeSearch(srcstr);
console.log(srcstr);
}
});
app.controller('AnimeListController', function(AnimeSearchService){
this.anime = AnimeSearchService.resultSet; //expose the service to the template (or optionally create a $watch to update)
this.onSelectAnime = function(anime){
console.log(anime);
};
});
UPDATE: Your issue most likely comes down to angular bindings. If you are binding to properties of the service's resultSet object then those bindings will update as those properties change. However, if you are assigning the value of a property to a new property in your own controller/scope then you will have to watch the service and update your controller/scope's copy. Perhaps this fiddle will help explain it better: http://jsfiddle.net/vv3odc7t/1/
There is also this stack overflow question about service binding in general: https://stackoverflow.com/a/23774843/1769529
Hope that helps!

Categories