import './common/directives/frSame'; import teamTypeahead from './common/directives/teamTypeahead'; angular.module('footyroom').requires.push('fr.same', teamTypeahead); angular.module('footyroom') .controller('RegistrationController', ['$scope', '$http', '$q', '$window', function ($scope, $http, $q, $window) { $scope.$watch('registrationForm', initForm); $scope.submit = function () { register(); }; function register() { // Don't perform server request if form is invalid. if ($scope.registrationForm.$invalid) { return; } // Show loader. $('.signup-well').litelay({ spinner: true }); // Reset server errors; delete $scope.serverErrors; $scope.user.gRecaptchaResponse = grecaptcha.getResponse(); // Make the server request. $http.post('/signup', $scope.user) .then(function (response) { if (!response.data.ok) { throw {}; } if ($scope.user.fbtoken) { $window.location = '/profile/settings'; } else { $window.location = '/signup/done'; } }) .catch(function (response) { if (typeof response.data === 'object') { _.each(response.data, function (errors, field) { if (field === 'server' || field === 'errors') { return $scope.serverErrors = errors; } _.each(errors, function (error) { if ($scope.registrationForm[field]) { $scope.registrationForm[field].$setValidity(error, false); } }); }); } else { $scope.serverErrors = ['Some unexpected error happened. Try again later.']; } $('.signup-well').litelay({ off: true }); grecaptcha.reset(); }); } function initForm() { $scope.user = { fbtoken: $.QueryString.fbtoken, }; // Username availability validator $scope.registrationForm.username.$asyncValidators.available = function (modelValue, viewValue) { // Consider empty models to be valid. if ($scope.registrationForm.username.$isEmpty(modelValue)) { return $q.when(); } // Make a request to the server to see of username is available. return $http.get('/signup/check-username', { params: { username: modelValue }, }) .then(function (response) { if (response.data != 'available') { throw 'FootyRoom: this username is not valid.'; } }); }; } }]);