I'm just getting started with Angular through a codeschool course. It's my first framework. I'm trying to build a very, very simple menu using ng-repeat. This very closely parallels the first project in the codeschool course, but it seems like I may have misunderstood something, or there may have been a concept that was inadequately covered at this point in the course. I've gone back and rewatched the videos that cover what I need to know to build this, and I cannot see what would be keeping this from working. I need to get the ball rolling here. Is it a mistake in my directives?
<html ng-app = 'menu'>
<body ng-controller = 'MenuController as menu'>
<section ng-repeat="menuItem in menu.menuItem">
<h1> {{menuItem.name}} </h1>
<p> {{menuItem.description}} </p>
<h3> {{menuItem.price}} </h3>
</section>
</body>
</html>
Heres the JS:
var app = angular.module('menu', []);
app.controller("MenuController", function(){
this.menuItem = appetizers;
});
var appetizers = [{
name : "Seared Ahi Tuna",
decription : "Cooked rare, thinly sliced and served over seaweed salad with a teriyaki glaze",
price : "12"
},
{
name : "Artisan Cheese Board",
decription : "Five chef-selected cheeses from WI farms (Sorry, no happy hour)",
price : "12"
}...
codepen
Your codepen has your script file as an IIFE, but it is missing the invocation () at the end, so it never runs. The code will run perfectly fine if you remove the IIFE Definition (function(){ ... }); or if you add the invocation to the end })();.
Note, this isn't directly related to Angular, it's more an issue of JavaScript Semantics... Don't let this put you off on using Angular!
Your error is Failed to instantiate module menu There are several possibilities of why you would get this error but in this case it is because it cannot find the module menu. If you look at your code
(function(){
var app = angular.module('menu', []);
....
});
notice you never actually call the anonymous function so the code never actually runs. All you have to do is call the function & everything works.
(function(){
var app = angular.module('menu', []);
....
})();
You have to execute the anonymous function as Austin said, but the code was also wrong. Usually it's better to inject you scope into the controller to make the item accessible from the ng-repeat command.
(function() {
var app = angular.module('menu', []);
app.controller("MenuController", function($scope) {
$scope.menuItem = appetizers;
});
var appetizers = [{
name: "Seared Ahi Tuna",
decription: "Cooked rare, thinly sliced and served over seaweed salad with a teriyaki glaze",
price: "12"
}, {
name: "Artisan Cheese Board",
decription: "Five chef-selected cheeses from WI farms (Sorry, no happy hour)",
price: "12"
}, {
name: "Oysters on the Half Shell*",
decription: "Fresh Blue Points from the Delaware Bay",
price: "1/2 Order 10, Full Dozen 16"
}, {
name: "Chorizo Sliders",
decription: "Three sliders on pretzel buns with sauteed onion, fried pickle chip and grained mustard",
price: "9"
}, {
name: "Tenderloin Lollipops*",
decription: "Served over a bed of red wine garlic mushrooms",
price: "10"
}]
})();
section {
border: 1px solid grey;
width: 50%;
margin: 0 auto;
}
<html ng-app='menu'>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body ng-controller='MenuController'>
<section ng-repeat="item in menuItem">
<h1> {{item.name}} </h1>
<p>{{item.description}}</p>
<h3> {{item.price}} </h3>
</section>
</body>
</html>
You need to include AngularJS Framework before using it and you are not injecting scope. The original call had anonymous function but not executing it.
var app = angular.module('menuApp', []);
app.controller("MenuController", ['$scope',
function($scope) {
$scope.appetizers = [{
name: "Seared Ahi Tuna",
decription: "Cooked rare, thinly sliced and served over seaweed salad with a teriyaki glaze",
price: "12"
}, {
name: "Artisan Cheese Board",
decription: "Five chef-selected cheeses from WI farms (Sorry, no happy hour)",
price: "12"
}, {
name: "Oysters on the Half Shell*",
decription: "Fresh Blue Points from the Delaware Bay",
price: "1/2 Order 10, Full Dozen 16"
}, {
name: "Chorizo Sliders",
decription: "Three sliders on pretzel buns with sauteed onion, fried pickle chip and grained mustard",
price: "9"
}, {
name: "Tenderloin Lollipops*",
decription: "Served over a bed of red wine garlic mushrooms",
price: "10"
}];
$scope.menu = $scope.appetizers;
}
]);
section {
border: 1px solid grey;
width: 50%;
margin: 0 auto;
}
<html ng-app='menuApp'>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.12/angular.min.js"></script>
</head>
<body ng-controller='MenuController'>
<section ng-repeat="menuItem in menu">
<h1> {{menuItem.name}} </h1>
<p>{{menuItem.description}}</p>
<h3> {{menuItem.price}} </h3>
</section>
</body>
</html>
Related
Here's my code.
I have a movies related tab and when a specific movie is open in a browser, under the related tab, related movies should be there. I have the map functions ready which load all the movies I have in the map object. Wanted an if and else statement to pick the same genre of movies by using a getElementId to get the id genre of the current movie and compare it with the genre in the map objects. Hope am using the right terms
//create test div
const data = [{
name: "13 reasons why",
href: "13 reasons why.php",
img: "https://images.theconversation.com/files/170594/original/file-20170523-5763-161mnda.jpg",
describe: "Newcomer Katherine Langford plays the role of Hannah, a young woman who takes her own life. Two weeks after her tragic death, a classmate named Clay finds a mysterious box on his porch. Inside the box are recordings made by Hannah -- on whom Clay had a crush -- in which she explains the 13 reasons why she chose to commit suicide. If Clay decides to listen to the recordings, he will find out if and how he made the list. This intricate and heart-wrenching tale is told through Clay and Hannah's dual narratives.",
rate: "7.6",
date: "(2017 - 2020)"
}, {
name: "30 Coins",
href: "30 coins.php",
img: "https://www.themoviedb.org/t/p/w500/b2i9aaV6ncULl9jYXEoPi7VFJg8.jpg",
describe: "Father Vergara, an exorcist, boxer and ex-convict exiled to a remote town in Spain, enlists the help of the mayor and a veterinarian when a series of paranormal phenomena begins to occur.",
rate: "7.2",
date: "(2020 - Present)"
}, {
name: "911 Lone Star",
href: "911 lone star.php",
img: "https://m.media-amazon.com/images/I/717AkBpHNjL._AC_SY450_.jpg",
describe: "9-1-1: Lone Star follows a sophisticated New York firefighter who, along with his son, relocates from Manhattan to Austin, Texas. He must try to balance the duties of saving those who are at their most vulnerable and solving the problems in his own life. ",
rate: "6.8",
date: "(2017 - 2021)"
}, {
name: "911",
href: "911.php",
img: "https://m.media-amazon.com/images/M/MV5BMzNiMmNmZWQtMTJlMS00NWIyLTlhNmEtNmI3M2Q1YjczMGI4XkEyXkFqcGdeQXVyNjEwNTM2Mzc#._V1_.jpg",
describe: "Policemen, paramedics and firefighters put themselves in dangerous situations to save people's lives. Meanwhile, they also have to deal with their personal problems.",
rate: "7.6",
date: "(2018 - Present)"
}, {
name: "A confession",
href: "a confession.php",
img: "https://m.media-amazon.com/images/M/MV5BZTc0ZjQxOWEtNTc4MS00ZjgxLThkOWEtZGM1NzgzOWYwOTc1XkEyXkFqcGdeQXVyMTAyNjU1NjU5._V1_.jpg",
describe: "The true story of DS Stephen Fulcher and his hunt for missing 22-year-old Sian O'Callaghan, and how it lead to the arrest of Christopher Halliwell. This was the beginning of the capture of a prolific serial killer and the detectives own downfall.",
rate: "7.6",
date: "(2019)"
}, {
name: "A million little things",
href: "a million little things.php",
img: "http://www.gstatic.com/tv/thumb/tvbanners/17114373/p17114373_b_v12_aa.jpg",
describe: "The lives of a group of carefree friends from Boston change when one of them shockingly dies. They soon realise the importance of cherishing their friendship.",
rate: "7.9",
date: "(2018)"
}, {
name: "A teacher",
href: "a teacher.php",
img: "https://m.media-amazon.com/images/M/MV5BZjgzMmUwZjgtNzNhMi00M2Y0LWIxOTAtYzYzODdjMTYzZWQyXkEyXkFqcGdeQXVyMTIwNDUyNzMy._V1_.jpg",
describe: "This drama series examines the complexities and consequences of an illicit sexual affair between a young teacher and her student. Claire is a new teacher at Westerbrook High School in Texas. Dissatisfied in her marriage to her college sweetheart, Claire's life changes when Eric, a personable teenager in her English class, takes an interest in her. Popular and outgoing, Eric is the captain of the soccer team and nearly inseparable from his best friends. Everything seems perfect on the surface, but Eric is forced to juggle the pressures of school, applying for college and a part-time job, all while helping take care of his two younger brothers. Claire and Eric discover an undeniable connection that allows them to escape their lives, but their relationship accelerates faster than either could anticipate. The permanent damage left in the wake of their illicit affair becomes impossible for them, and their friends and family, to ignore.",
rate: "6.9",
date: "(2020)"
}, {
name: "Absentia",
href: "absentia.php",
img: "https://m.media-amazon.com/images/M/MV5BNmFiNDI5ODUtODQ2ZC00ZjUwLWFhYjQtMjk3MmMzZjY1ZWU2XkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: ">Six years after going missing and being declared dead, FBI agent Emily Byrne is found alive in a cabin in the woods. With no memory of her past, she sets out to reclaim her life and identity.",
rate: "7.3",
date: "(2017 - 2020)"
}, {
name: "After Life",
href: "after life.php",
img: "https://m.media-amazon.com/images/M/MV5BZjdjOWIxMDgtYTgwNS00MjE4LTliZWYtZGI1NDhhZmIyYjM1XkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: "Tony had a perfect life -- until his wife Lisa died. After that tragic event, the formerly nice guy changed. After contemplating taking his life, Tony decides he would rather live long enough to punish the world by saying and doing whatever he likes. He thinks of it as a superpower -- not caring about himself or anybody else -- but it ends up being trickier than he envisioned when his friends and family try to save the nice guy that they used to know. Golden Globe winner Ricky Gervais stars in the comedy series, which he also writes and directs.",
rate: "8.4",
date: "(2019 - 2020)"
}, {
name: "Alex Rider",
href: "alex rider.php",
img: "https://m.media-amazon.com/images/M/MV5BOTg4ZmQ5ZjItZTllZC00NzUzLTkwMTEtMjIzYzliZjk2ODUwXkEyXkFqcGdeQXVyMTEyMjM2NDc2._V1_.jpg",
describe: "London teenager Alex Rider is recruited by the Department of Special Operations, a subdivision of the Secret Intelligence Service (MI6), to infiltrate a controversial corrective academy for the wayward offspring of the ultra-rich.",
rate: "7.6",
date: "(2020)"
}, {
name: "All Rise",
href: "all rise.php",
img: "https://m.media-amazon.com/images/M/MV5BYTk5ZjI0M2MtYjQ5Ny00OWJmLWExYWEtNjRlMTdkNjYwMGIzXkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_.jpg",
describe: "A look inside the chaotic, hopeful and sometimes absurd lives of judges, prosecutors and public defenders as they work with bailiffs, clerks and cops to get justice for the people of Los Angeles amidst a flawed legal process. Among them is newly appointed Judge Lola Carmichael, a highly regarded and impressive deputy district attorney who doesn't intend to sit back on the bench in her new role, but instead leans in, immediately pushing the boundaries and challenging the expectations of what a judge can be.",
rate: "6.7",
date: "(2019 - 2021)"
}, {
name: "Altered Carbon",
href: "altered carbon.php",
img: "https://m.media-amazon.com/images/M/MV5BNjIxMWMzMzctYmZkYy00OTkzLWFlMWUtMjc3ZDFmYzQ3YmVkXkEyXkFqcGdeQXVyNjU2ODM5MjU#._V1_.jpg",
describe: "More than 300 years in the future, society has been transformed by new technology, leading to human bodies being interchangeable and death no longer being permanent. Takeshi Kovacs is the only surviving soldier of a group of elite interstellar warriors who were defeated in an uprising against the new world order. His mind was imprisoned for centuries until impossibly wealthy businessman Laurens Bancroft offers him the chance to live again. Kovacs will have to do something for Bancroft, though, if he wants to be resurrected. Bancroft's request of Kovacs is to solve a murder Bancroft's. 'Altered Carbon' is based on Richard K. Morgan's cyberpunk noir novel of the same name.",
rate: "8",
date: "(2018 - 2020)"
}, {
name: "American Horror Story",
href: "american horror story.php",
img: "https://flxt.tmsimg.com/assets/p9423798_b_v12_ad.jpg",
describe: "An anthology series centering on different characters and locations, including a house with a murderous past, an insane asylum, a witch coven, a freak show circus, a haunted hotel, a possessed farmhouse, a cult, the apocalypse, a slasher summer camp, and a bleak beach town and desert valley.",
rate: "7.6",
date: "(2011 - Present)"
}, {
name: "Anne With An E",
href: "anne with an e.php",
img: "https://m.media-amazon.com/images/M/MV5BNThmMzJlNzgtYmY5ZC00MDllLThmZTMtNTRiMjQwNmY0NmRhXkEyXkFqcGdeQXVyMTkxNjUyNQ##._V1_FMjpg_UX1000_.jpg",
describe: "This reimagining of the classic book and film is a coming-of-age story about a young orphan who is seeking love, acceptance and her place in the world. Amybeth McNulty stars as Anne, a 13-year-old who has endured an abusive childhood in orphanages and the homes of strangers. In the late 1890s, Anne is mistakenly sent to live with aging siblings, Marilla and Matthew Cuthbert, who live on Prince Edward Island. Anne, who proves to be uniquely spirited, imaginative and smart, transforms the lives of Marilla, Matthew and everyone else in their small town.",
rate: "8.7",
date: "(2017 - 2019)"
}, {
name: "animal kingdom",
href: "animal kingdom.php",
genre: "drama",
img: "https://m.media-amazon.com/images/M/MV5BOTk1NjAwOTM1OV5BMl5BanBnXkFtZTgwMzUwODQ3NzM#._V1_FMjpg_UX1000_.jpg",
describe: "After the death of his mother, Joshua decides to live with his grandmother, who heads a criminal clan. His life takes a turn as he gets involved with his cousins and their criminal activities.",
rate: "8.2",
date: "(2016 - Present)"
}, {
name: "Arrow",
href: "arrow.php",
genre: "drama",
img: "https://m.media-amazon.com/images/M/MV5BMTI0NTMwMDgtYTMzZC00YmJhLTg4NzMtMTc1NjI4MWY4NmQ4XkEyXkFqcGdeQXVyNTY3MTYzOTA#._V1_.jpg",
describe: "After mastering the skill of archery on a deserted island, multi-millionaire playboy Oliver Queen returns to his city to take on the vigilante persona of Arrow to fight crime and corruption.",
rate: "7.5",
date: "(2012 - 2020)"
}, {
name: "Atypical",
href: "atypical.php",
img: "https://m.media-amazon.com/images/M/MV5BMjNjNThmYTUtMjY2Ni00OGE4LTgzOTItYTgzMDllNDM5NTI5XkEyXkFqcGdeQXVyNjEwNTM2Mzc#._V1_FMjpg_UX1000_.jpg",
describe: "This heartfelt comedy follows Sam, a teenager on the autism spectrum, who has decided he is ready for romance. In order to start dating -- and hopefully find love -- Sam will need to be more independent, which also sends his mother (Jennifer Jason Leigh) on her own life-changing path. She and the rest of Sam's family, including a scrappy sister and a father seeking a better understanding of his son, must adjust to change and explore what it means to be normal. The series is created and written by Robia Rashid and Academy Award-winning producer Seth Gordon.",
rate: "8.3",
date: "(2017 - 2021)"
}]
const createTest = (selector) => {
const test = document.querySelector(selector)
console.log(selector)
let html = ''
data.map(({
id,
name,
href,
img,
describe,
rate,
date
}, index) => {
html = `
${html}
<div class="movie-item-style-2">
<div id="product${index}" class="mv-item-infor">
<img src="${img}" alt="">
<h6 style="padding-top: 1em;">${name} <span>${date}</span></h6>
<p class="rate"><i class="ion-android-star"></i><span>${rate}</span> /10</p>
<p class="describe">${describe}</p>
</div>
</div>
`
})
test.innerHTML = html
}
createTest(".content")
<div id="moviesrelated" class="tab">
<div class="row">
<h3>Related Movies</h3>
<div class="test"></div>
<div class="topbar-filter">
<p>Found <span>12 movies</span> in total</p>
<label>Sort by:</label>
<select>
<option value="popularity">Popularity Descending</option>
<option value="popularity">Popularity Ascending</option>
<option value="rating">Rating Descending</option>
<option value="rating">Rating Ascending</option>
<option value="date">Release date Descending</option>
<option value="date">Release date Ascending</option>
</select>
</div>
<div class="content">
</div>
<div class="topbar-filter">
<label>Movies per page:</label>
<select>
<option value="range">5 Movies</option>
<option value="saab">10 Movies</option>
</select>
<div class="pagination2">
<span>Page 1 of 2:</span>
<a class="active" href="#">1</a>
2
<i class="ion-arrow-right-b"></i>
</div>
</div>
</div>
</div>
I want to display my json data with sliding feature. Here is the design of what i want to do. I saw carousel is for sliding images but i don't know how to achieve this one. Any help would be great.
And here is sample code.
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.myDatas = [{
Paramnames: "Travel Material",
options: [{
name: "Newspaper"
},
{
name: "Magazine"
},
{
name: "Book"
}
]
},
{
Paramnames: "Safety & Security",
options: [{
name: "Health"
},
{
name: "Private Policy"
},
{
name: "Flight Disruption"
}
]
}
];
});
<div ng-app="myApp" ng-controller="myCtrl">
<div class="col-sm-3" ng-repeat="myData in myDatas">
<p class="m-t-xs font-bold"><strong>{{myData.Paramnames}} </strong></p>
<div class="col-sm-8" ng-repeat="myOptions in myData.options">
<p class="m-t-xs font-bold">{{myOptions.name}}
</p>
</div>
</div>
</div>
I finally found an answer for my question. I thought it might help i used angular-slick directive its so cool. http://vasyabigi.github.io/angular-slick/
I'm trying to make a simple grammar quiz, but I'm having trouble figuring out how to sort array randomly while using ng-repeat. I would like to display both "Correct" sentence and "Incorrect" sentences and want them to be sorted in randomly.
You can check my code && data below:
(function(angular) {
'use strict';
angular.module('demo', ['ngAnimate'])
.controller('repeatController', function($scope) {
$scope.random = function() {
return 0.5 - Math.random();
};
$scope.questions = {
"0": {
"Category": "Commas",
"Correct": "Shirley Chisholm was the first major-party candidate to run for President in a major party. She ran as a Democrat.",
"Given_sen": "\"Shirley Chisholm was the first major party candidate to run for President in a major party, she ran as a Democrat.\"",
"Incorrect": [
"\"Shirley Chisholm, the first major-party candidate to run for President in a major party, she ran as a Democrat.\"",
"Shirley Chisholm was the first major-party candidate to run for President in a major party: she ran as a Democrat.",
"Shirley Chisholm was the first major-party candidate to run for President in a major party (she ran as a Democrat)."
],
"Question": "Fix the comma splice.",
"Rule": "comma splice\n"
},
"1": {
"Category": "Commas",
"Correct": "Hattie McDaniel was the first African-American to win an Oscar. She won for her performance in Gone with the Wind.",
"Given_sen": "\"Hattie McDaniel was the first African-American to win an Oscar, she won for her performance in Gone with the Wind.\"",
"Incorrect": [
"Hattie McDaniel was the first African-American to win an Oscar: she won for her performance in Gone with the Wind.",
"\"Hattie McDaniel, the first African-American to win an Oscar, she won for her performance in Gone with the Wind.\"",
"\"Hattie McDaniel was the first African-American to win an Oscar, for her performance in Gone with the Wind.\""
],
"Question": "Fix the comma splice.",
"Rule": "comma splice\n"
}
};
});
})(window.angular);
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular-animate.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
</head>
<body ng-app="demo">
<div ng-controller="repeatController">
<form ng-repeat="question in questions">
<div class="well"><b> QUESTION: {{question.Question}}</b>
<br> Category: {{question.Category}} </div>
<div ng-repeat="incorrect_answer in question.Incorrect">
<input type="radio" name="radio{{$parent.$index}}" value="{{incorrect_answer}}">{{incorrect_answer}}</input>
</div>
<div>
<input type="radio">{{question.Correct}} </input>
</div>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
Also if you can provide me the way to use "submit" button to find the correct answer, it would be wonderful! Right now, I am not sure how to find out the way to check whether the submitted answer is equal to "Correct" one.
There are some mistakes:
<input> is a self-closing tag;
You forgot to call your function in your view like as below:
<div ng-repeat="incorrect_answer in random(question.Incorrect)">
You have to return the array shuffled in your function:
$scope.random = function(array) {
return array.sort(function() {
return .5 - Math.random();
});
}
(function(angular) {
'use strict';
angular.module('demo', [])
.controller('repeatController', function($scope) {
$scope.questions = {
"0": {
"Category": "Commas",
"Correct": "Shirley Chisholm was the first major-party candidate to run for President in a major party. She ran as a Democrat.",
"Given_sen": "\"Shirley Chisholm was the first major party candidate to run for President in a major party, she ran as a Democrat.\"",
"Incorrect": [
"\"Shirley Chisholm, the first major-party candidate to run for President in a major party, she ran as a Democrat.\"",
"Shirley Chisholm was the first major-party candidate to run for President in a major party: she ran as a Democrat.",
"Shirley Chisholm was the first major-party candidate to run for President in a major party (she ran as a Democrat)."
],
"Question": "Fix the comma splice.",
"Rule": "comma splice\n"
},
"1": {
"Category": "Commas",
"Correct": "Hattie McDaniel was the first African-American to win an Oscar. She won for her performance in Gone with the Wind.",
"Given_sen": "\"Hattie McDaniel was the first African-American to win an Oscar, she won for her performance in Gone with the Wind.\"",
"Incorrect": [
"Hattie McDaniel was the first African-American to win an Oscar: she won for her performance in Gone with the Wind.",
"\"Hattie McDaniel, the first African-American to win an Oscar, she won for her performance in Gone with the Wind.\"",
"\"Hattie McDaniel was the first African-American to win an Oscar, for her performance in Gone with the Wind.\""
],
"Question": "Fix the comma splice.",
"Rule": "comma splice\n"
}
};
function sort(array) {
return array.sort(function() {
return .5 - Math.random();
});
}
function random() {
for (var key in $scope.questions) {
$scope.questions[key].Incorrect = sort($scope.questions[key].Incorrect);
}
}
random();
});
})(angular);
<!DOCTYPE html>
<html ng-app="demo">
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body ng-controller="repeatController">
<form ng-repeat="question in questions">
<div class="col-md-12">
<div class="well"><b> QUESTION: {{question.Question}}</b>
<br> Category: {{question.Category}} </div>
<div class="radio" ng-repeat="incorrect_answer in question.Incorrect">
<label>
<input type="radio" name="radio{{$parent.$index}}" value="{{incorrect_answer}}"> {{incorrect_answer}}
</label>
</div>
<div class="form-group">
<label class="radio-inline">
<input type="radio"> {{question.Correct}}
</label>
</div>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Submit">
</div>
</div>
</form>
</body>
</html>
EDIT:
As pointed out by #charlietfl, it's better to loop over the whole object and shuffle the array once in controller to prevent digest problems.
I think it's better to handle your items if you mix all questions (correct and incorrect) in an unique array.
I think you have to create a array of possible answers and correct answer and use the randomize algorithams like https://github.com/coolaj86/knuth-shuffle
Or you can you method like specified in the below post.
ng-repeat changing sort order on all items when new item added to model
When you submit the data you can verify it in couple of ways.
you can pass the value of selected radio button and question identifier if any or index of the question compare with the actual correct answer field in the questions array.
You can store the question identifier and selected answer and send it to the server to verify.
I hope it helps you.
You can create a list of possible answers, shuffle the list and loop over them. You can also have a field for the correct answer. So instead of excluding the correct answer from the list, include them with the other ones and just shuffle it with an algorithm like knuth. So your model could look something like this:
$scope.model = {
randomize: function (arr) {
return knuthShuffle(arr.slice(0));
},
questions: [
{
id: 1,
title: 'Title of the question',
possibleAnswers: [{ name: 'Tom' }, { name: 'John' }, { name: 'Kim' }, { name: 'Tim' }],
correctAnswer: { name: 'John' }
}
]
};
and then in your view you could do something like:
<ul>
<li ng-repeat="question in model.questions">
<ul>
<li ng-repeat="possibleAnswer in model.randomize(question.possibleAnswers)">
{{possibleAnswer}}
</li>
</ul>
</li>
</ul>
and to verify the answer you can have field to store the selected answer and pass it along to the backend:
selectedAnswer: {'name': 'John'}
the method on the controller would then call your service:
vm.verifyAnswer(model.selectedAnswer, correctAnswer)
This is part of my JSON file
{
"topic": {
"topicTitle": "Living things and the environment",
"subTopics": [
{
"subTopicTitle": "Identifying, namimg and classifying",
"subTopicShortName": "identifyingNamingClassifying",
"subTopicDescription": "About one and a half million kinds of organisms have been discovered. How do we identify, name and classify them?",
"subTopicQuestions": [
{
"question": "Use the key to identify the plants a to e in picture 1.",
"subTopicQuestionAssetLinks": [
"href://file/filename/image1.jpeg"
],
"subTopicQuestionAssetCaptions": [
"Caption 1"
]
},
And this is my javascript
<script>
$.getJSON('data.json', function(data1) {
intro_template = "<h1> {{topic.topicTitle}} </h1> <h2> {{topic.subTopics}} </h2>";
html = Mustache.to_html(intro_template, data1);
$('.intro_template_container').html(html);
});
</script>
The h1 works perfectly displaying "Living things and the environment"
Beween the H2 tags I would like to show the "subTopicTitle" of "identifying, name and classifying"
How is this possible?
Since subTopics is an array, you will have to use a mustache section:
<h1>{{topic.topicTitle}}</h1>
{{#topic.subTopics}}
<h2>{{subTopicTitle}}</h2>
{{/topic.subTopics}}
I am new at learning code - so please be patient. I am attempting to create a Jeopardy style game for my wife (who is a school teacher). However, I am running into a problem. I would like to click on a link ($100, etc.) and have the clue (value) logged into a div on a separate page. Through my research, I have settled on creating a JSON object from an array and then have the JSON parsed for index and value.
Here is my HTML:
<ul id="rowOne">
<li>$100</li>
<li>$100</li>
<li>$100</li>
<li>$100</li>
<li>$100</li>
</ul>
Here is the div where I would like the value logged:
<div id="clueContainer" class="center"></div>
Here is my Jquery:
$(document).ready(function(){
var rowOne = array [
{name:"$100", value:"On the world political map, where were some of the major states and empires located about 1500 A.D. (C.E.)?"},
{name:"$200", value:"What were the artistic, literary, and intellectual ideas of the Renaissance?"},
{name:"$300", value:"Where were the five world religions located around 1500 A.D. (C.E.)?"},
{name:"$400", value:"What were the regional trading patterns about 1500 A.D. (C.E.)?"},
{name:"$500", value:"Why were the regional trading patterns important?",}
];
var json = JSON.parse(rowOne);
$("li a href").click(function(){
$.each(json, function(index, value){
$("#clueContainer").append(function(){
$(value).log(<p>+value+</p>);
});
});
});
});
Are there any ideas out there or an I approaching this project the wrong way?
You have the right idea for arrays but the syntax is a little different than what you have. I've created an array of array of objects. The structure is similar to this:
var arr = [[
{
property: value
}, {
property: value
}][{
property: value
}, {
property: value
}]
];
I added a class called rows to the ul element and you can then iterate over that with each() using jQuery's built in index (p in our case) and then iterate over the number of a elements in the ul to add a question from the rows array.
$(document).ready(function () {
var rows = [
[{
name: "$100",
value: "On the world political map, where were some of the major states and empires located about 1500 A.D. (C.E.)?"
}, {
name: "$200",
value: "What were the artistic, literary, and intellectual ideas of the Renaissance?"
}, {
name: "$300",
value: "Where were the five world religions located around 1500 A.D. (C.E.)?"
}, {
name: "$400",
value: "What were the regional trading patterns about 1500 A.D. (C.E.)?"
}, {
name: "$500",
value: "Why were the regional trading patterns important?"
}],
[{
name: "$100",
value: "Who cares about the price of tea in China?"
}, {
name: "$200",
value: "Why did the chicken cross the road?"
}, {
name: "$300",
value: "How much wood could a woodchuck chuck if a woodchuck could chuck wood?"
}, {
name: "$400",
value: "How many SEO specialists does it take to change a light, bulb, lightbulb, energy, electricity?"
}, {
name: "$500",
value: "Where in the world is Carmen San Diego?"
}]
];
$(".rows").each(function (p) {
$("#row" + p).find("a").each(function (i) {
$(this).text(rows[p][i].name);
$(this).click(function () {
var value = rows[p][i].value;;
$("#clueContainer").html(value);
});
});
});
});
jsFiddle
I'm not familiar with jeopardy, but the list should contain the values from $100 to $500?
I modified your code, assuming the list is ascending: fiddle
No fiddle without code:
$(document).ready(function () {
var rowOne = {
"$100": "On the world political map, where were some of the major states and empires located about 1500 A.D. (C.E.)?",
"$200": "What were the artistic, literary, and intellectual ideas of the Renaissance?",
"$300": "Where were the five world religions located around 1500 A.D. (C.E.)?",
"$400": "What were the regional trading patterns about 1500 A.D. (C.E.)?",
"$500": "Why were the regional trading patterns important?"
};
$("li").on('click', 'a', function () {
var foo = $(this).text();
$('#clueContainer').text( rowOne[foo] );
});
});