frPoll.js 1.68 KB
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;
                });
            }
        }],
    };
}]);