Skip to content

Instantly share code, notes, and snippets.

@bendrucker
Created May 16, 2014 18:58
Show Gist options
  • Save bendrucker/faa80cf843cb53e9eae7 to your computer and use it in GitHub Desktop.
Save bendrucker/faa80cf843cb53e9eae7 to your computer and use it in GitHub Desktop.
Angular forms
'use strict';
angular.module('quizApp')
.factory('Question', function () {
var Question = function (question, answers, correct_answer) {
this.question = question;
this.answers = [];
this.correct_answer = correct_answer;
};
Question.prototype.isCorrect = function () {
return this.selected_answer === this.correct_answer;
};
Question.prototype.isAnswered = function () {
return typeof this.selected_answer !== 'undefined';
};
Question.prototype.selectAnswer = function (answer) {
this.selected_answer = answer;
return this;
};
return Question;
});
'use strict';
angular.module('quizApp')
.controller('QuizCtrl', function ($scope, Quiz, Question) {
$scope.quiz = new Quiz('JS Quiz');
$scope.question = new Question();
$scope.addAnswer = function (question, answer) {
question.answers.push(answer.text);
if (answer.correct) question.correct_answer_index = question.answers.length - 1;
$scope.answer = {};
};
$scope.displayColor = function (question) {
if (!question.isAnswered()) return 'black';
return question.isCorrect() ? 'green' : 'red';
};
});
'use strict';
angular.module('quizApp')
.factory('Quiz', function () {
var Quiz = function (name) {
this.name = name;
this.questions = [];
};
return Quiz;
});
<h1>{{quiz.name}}</h1>
<form name="myForm" ng-submit="quiz.questions.push(question)">
<h1>{{myForm.$valid}}</h1>
<input type="text" placeholder="Question" ng-model="question.question" required minlength="10" />
<input type="text" placeholder="Answer" ng-model="answer.text" ng-repeat="i in [0,1,2,3]" />
<!-- <label>Correct <input type="checkbox" ng-model="answer.correct" /></label> -->
<button type="button" ng-click="addAnswer(i, question, answer)">Add Answer</button>
<div>
<button type="submit" ng-disabled="myForm.$invalid">Add Question</button>
</div>
</form>
<div ng-repeat="question in quiz.questions">
<p ng-style="{color: displayColor(question)}">{{question.question}}</p>
<button
ng-repeat="answer in question.answers"
ng-click="question.selectAnswer(answer)"
ng-disabled="question.isAnswered()"
>
{{answer}}
</button>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment