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)
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 am trying to learn/use Node and Javascript by re-coding a PHP/MYSQL application I made that is not very efficient - as I built it while I was trying to earn those technologies as well.
I am trying to re-use a some of the information that is created or stored in JSON format.
I have in one file a set of 52 questions that looks like such...
//questions.json
{
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
},
"Administration" : {
"Question 9": "Administration positively supports faculty in a professional manner.",
"Question 10": "Administration actively encourages a dialogue concerning school related issues.",
"Question 11": "Administration is actively engaged in developing/supporting/maintaining a clear school vision.",
"Question 12": "Administration makes sure that the financial stability and integrity of the school is well maintained.",
"Question 13": "Administration/Ownership uses school funds to support the well being of the school."
},...
I also have a Knex script that does a query on the data and returns an array like below....
[ { Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5,
Q9: 7.63,
Q10: 8.13,
Q11: 8.5,
Q12: 8.88,
Q13: 8.75,
Q14: 7.38,
Q15: 8.13,
Q16: 8.56,...
I would like to try to combine these two arrays to look like...
{
"School" : {
{"Question 1" : {
"Question" : "The facilities of the school adequately provide for a positive learning/working experience.",
"Average" : 8.44
},
{"Question 2" : {
"Question" : ""School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc."",
"Average" : 9.13
}
If need be I can remove the category divisions within the .json file if that make combining easier, but in the end applications I display the data in sections, so I will eventually filter it. I just thought maybe dividing it in the json file would make it easier.
I am able to concat the arrays, and I have looked at .map but I am not sure how I would apply it to this. It looks like I would need a nested loop?
Using a double forEach loop:
const questions = {
"School" : {
"Question 1": "The facilities of the school adequately provide for a positive learning/working experience.",
"Question 2": "School provides adequate access to teaching materials without any extra expense by the teacher (books, lab supplies, art supplies, materials, copying, etc.",
"Question 3": "School is well funded to provide students and faculty with adequate materials to support their course offering.",
"Question 4": "Parent community is actively involved in supporting the school's mission and their child's education endeavors.",
"Question 5": "Classroom student to teacher ratios are kept low."
},
"Students" : {
"Question 6": "Students are generally of high aptitude.",
"Question 7": "Student interactions with faculty are primarily characterized by respectability.",
"Question 8": "Students are of diverse ethnicity."
}
};
const scores = {
Q1: 8.44,
Q2: 9.13,
Q3: 8.81,
Q4: 8.38,
Q5: 7.63,
Q6: 8.06,
Q7: 8.56,
Q8: 8.5
};
// Placeholder for your result
const result = {};
// Iterate through the question categories:
const categories = Object.keys(questions);
categories.forEach(cat => {
// Add category to result
result[cat] = {};
// Get the question keys for that category
const questionKeys = Object.keys(questions[cat]);
questionKeys.forEach(q => {
// Get the score key. i.e: Question 1 -> Q1
const scoreKey = q.replace('Question ', 'Q');
// Add question to result
result[cat][q] = {
Question: questions[cat][q],
Average: scores[scoreKey]
};
});
});
console.log(result);
What I do below is basically:
I take the question number out of "Question 1"
Combine it with "Q" to get "Q1"
And then the plain old key lookup in the object you have based on this new string.
All this, in loops below
var newObj = {};
// replace /*questions.json*/ with your actual object.
for (var category in /*questions.json*/){
var questionsObj = /*questions.json*/[category];
newObj[category] = {}
for (var question in questionsObj) {
newObj[category][question] = {};
newObj[category][question].question = questionsObj[question];
var qNumber = question.split("Question ")[1];
newObj[category][question].Average = dataArray[0]["Q"+qNumber];
}
}
I am looking to loop through an object and input into certain indexes using jQuery. I am using Sweet Alert 2 and the chaining modals but I need to generate the titles dynamically. The titles are in the array below.
The object used by SA2 is the following:
var steps = [{
title: 'Questions',
input: 'radio',
inputOptions: inputOptions,
}]
I guess 'each' of some kind after the squared bracket.
["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
Essentailly I need to create:
var steps = [{
title: 'Washing Machine diagnosis',
input: 'radio',
inputOptions: inputOptions,
},
{
title: 'Washing Machine diagnosis',
input: 'radio',
inputOptions: inputOptions,
}]
Thank you for any help
You can use Array.map()
es6
var result = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
.map(e => ({title:e,input:"radio",inputOptions:{}}));
console.log(result)
es5
var result = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
.map(function(e){
return {title:e,input:"radio",inputOptions:{}};
});
console.log(result)
You need a template object:
var step = {
title : '',
input : 'radio',
inputOptions : inputOptions
};
Then you will just iterate through the array:
var titles = [
"Washing Machine diagnosis",
"Washing Machine type",
...
"Do you have a receipt?"
];
var steps = titles.map((title) => {
var clone = Object.assign({}, step);
clone.title = title;
return clone;
});
or just use Underscore.js to clone objects if you do not like assign()
How about this
$.each(steps, function(i, step){
step.title = myArray[i];
});
This uses JQuery to loop through the array.
I'm not sure i've understand your question but how about this
const titles = ["Washing Machine diagnosis", "Washing Machine type", "Have you ever had an engineer look at this fault?", "Has an engineer looked at this appliance in the last 6 months?", "Has anybody that is not a qualified repair engineer attempted to repair the Washing Machine?", "Duration of problem", "When did you purchase this Washing Machine?", "Do you have a receipt?"]
const steps = titles.map((title) => {
return {
title,
input: 'radio',
inputOptions
}
})
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>
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}}