frPoll.js
1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
angular.module('footyroom')
.directive('frPoll', [function () {
return {
templateUrl: '/views/ng/poll/poll.html?2',
scope: {
frPoll: '@',
},
controllerAs: 'ctrl',
bindToController: true,
controller: ['$http', function ($http) {
var ctrl = this;
ctrl.$onInit = $onInit();
ctrl.toggleResults = toggleResults;
ctrl.vote = vote;
function $onInit() {
fetchPoll(ctrl.frPoll);
}
function fetchPoll(pollId) {
return $http.get('/polls/' + pollId)
.then(function (response) {
ctrl.poll = response.data;
ctrl.selectedChoice = ctrl.poll.userVote;
ctrl.showPollResult = ctrl.poll.userVote >= 0;
});
}
function toggleResults() {
ctrl.showPollResult = !ctrl.showPollResult;
}
function vote() {
if (ctrl.voting) {
return;
}
ctrl.voting = true;
var vote = {
pollRef: 'poll-' + ctrl.poll.id,
choices: [{ value: ctrl.selectedChoice }],
};
$http.post('/vote-poll', vote)
.then(function () {
return fetchPoll(ctrl.frPoll);
})
.catch(function (response) {
ctrl.errors = response.data.errors;
})
.finally(function () {
ctrl.voting = false;
});
}
}],
};
}]);