I found a helpful AngularJS+ASP.NET tutorial that introduces the concept of $scope
, but I am interested in using the newer syntax controller
instead. I came across a useful discussion on this topic in a question titled: "AngularJs "controller as" syntax - clarification?"
However, my attempt to implement this change is currently not functioning as expected. The issue lies in the page's invocation of $http.get
within the nextQuestion()
function, yet the view remains static with only the title displaying as "loading question..."
.
Below is the code snippet:
JS http://pastebin.com/RfngRuZD
var app = angular.module('QuizApp', [])
app.controller('QuizCtrl', ['$http', function ($http) {
this.answered = false;
this.title = "loading question...";
this.options = [];
this.correctAnswer = false;
this.working = false;
this.answer = function () {
return this.correctAnswer ? 'correct' : 'incorrect';
};
// GET
this.nextQuestion = function () {
this.working = true;
this.answered = false;
this.title = "loading question...";
this.options = [];
$http.get('/api/trivia').success(function (data, status, headers, config) {
this.options = data.options;
this.title = data.title;
this.answered = false;
this.working = false;
}).error(function (data, status, headers, config) {
this.title = "Oops... something went wrong.";
this.working = false;
});
};
// POST
this.sendAnswer = function (option) {
this.working = true;
this.answered = true;
$http.post('/api/trivia', { 'questionId': option.questionId, 'optionId': option.id }).success(function (data, status, headers, config) {
this.correctAnswer = (data === "true");
this.working = false;
}).error(function (data, status, headers, config) {
this.title = "Oops... something went wrong.";
this.working = false;
});
};
}]);
Index.cshtml http://pastebin.com/YmV1hwcU
@{
ViewBag.Title = "Play";
}
<div id="bodyContainer" ng-app="QuizApp">
<section id="content">
<div class="container">
<div class="row">
<div class="flip-container text-center col-md-12" ng-controller="QuizCtrl as quiz" ng-init="quiz.nextQuestion()">
<div class="back" ng-class="{flip: quiz.answered, correct: quiz.correctAnswer, incorrect: !quiz.correctAnswer}">
<p class="lead">{{quiz.answer()}}</p>
<p>
<button class="btn btn-info btn-lg next option" ng-click="quiz.nextQuestion()" ng-disabled="quiz.working">Next Question</button>
</p>
</div>
<div class="front" ng-class="{flip: quiz.answered}">
<p class="lead">{{quiz.title}}</p>
<div class="row text-center">
<button class="btn btn-info btn-lg option"
ng-repeat="option in quiz.options" ng-click="quiz.sendAnswer(option)" ng-disabled="quiz.working">
{{option.title}}
</button>
</div>
</div>
</div>
</div>
</div>
</section>
</div>
@section scripts{
@Scripts.Render("~/Scripts/angular.js")
@Scripts.Render("~/Scripts/app/quiz-controller.js")
}