2014-07-08 07:02:26 -04:00
|
|
|
define [
|
|
|
|
"base"
|
|
|
|
], (App) ->
|
|
|
|
App.directive "asyncForm", ($http) ->
|
|
|
|
return {
|
|
|
|
link: (scope, element, attrs) ->
|
|
|
|
formName = attrs.asyncForm
|
|
|
|
|
|
|
|
scope[attrs.name].response = response = {}
|
2014-07-11 12:08:19 -04:00
|
|
|
scope[attrs.name].inflight = false
|
2014-07-08 07:02:26 -04:00
|
|
|
|
|
|
|
element.on "submit", (e) ->
|
|
|
|
e.preventDefault()
|
|
|
|
|
|
|
|
formData = {}
|
|
|
|
for data in element.serializeArray()
|
|
|
|
formData[data.name] = data.value
|
|
|
|
|
2014-07-11 12:08:19 -04:00
|
|
|
scope[attrs.name].inflight = true
|
|
|
|
|
2014-07-08 07:02:26 -04:00
|
|
|
$http
|
|
|
|
.post(element.attr('action'), formData)
|
|
|
|
.success (data, status, headers, config) ->
|
2014-07-11 12:08:19 -04:00
|
|
|
scope[attrs.name].inflight = false
|
2014-07-08 07:02:26 -04:00
|
|
|
response.success = true
|
|
|
|
response.error = false
|
|
|
|
|
|
|
|
if data.redir?
|
|
|
|
ga('send', 'event', formName, 'success')
|
|
|
|
window.location = data.redir
|
|
|
|
else if data.message?
|
|
|
|
response.message = data.message
|
|
|
|
|
|
|
|
if data.message.type == "error"
|
|
|
|
response.success = false
|
|
|
|
response.error = true
|
|
|
|
ga('send', 'event', formName, 'failure', data.message)
|
|
|
|
else
|
|
|
|
ga('send', 'event', formName, 'success')
|
2014-07-11 12:08:19 -04:00
|
|
|
|
2014-07-08 07:02:26 -04:00
|
|
|
.error (data, status, headers, config) ->
|
2014-07-11 12:08:19 -04:00
|
|
|
scope[attrs.name].inflight = false
|
2014-07-08 07:02:26 -04:00
|
|
|
response.success = false
|
|
|
|
response.error = true
|
|
|
|
response.message =
|
2014-07-11 12:08:19 -04:00
|
|
|
text: data.message?.text or "Something went wrong talking to the server :(. Please try again."
|
2014-07-08 07:02:26 -04:00
|
|
|
type: 'error'
|
|
|
|
ga('send', 'event', formName, 'failure', data.message)
|
|
|
|
}
|
|
|
|
|
|
|
|
App.directive "formMessages", () ->
|
|
|
|
return {
|
|
|
|
restrict: "E"
|
|
|
|
template: """
|
|
|
|
<div class="alert" ng-class="{
|
|
|
|
'alert-danger': form.response.message.type == 'error',
|
|
|
|
'alert-success': form.response.message.type != 'error'
|
|
|
|
}" ng-show="!!form.response.message">
|
|
|
|
{{form.response.message.text}}
|
|
|
|
</div>
|
|
|
|
<div ng-transclude></div>
|
|
|
|
"""
|
|
|
|
transclude: true
|
|
|
|
scope: {
|
|
|
|
form: "=for"
|
|
|
|
}
|
|
|
|
|
2014-07-11 12:08:19 -04:00
|
|
|
}
|