Skip to content

Instantly share code, notes, and snippets.

@glebm
Last active December 17, 2015 19:09
Show Gist options
  • Save glebm/5658158 to your computer and use it in GitHub Desktop.
Save glebm/5658158 to your computer and use it in GitHub Desktop.
AngularJS Form Helper
angular.module('myApp').factory 'FormHelper', [->
class FormHelper
constructor: (scope, object, formName) ->
@scope = scope
@formName = formName
@object = -> @scope[object]
scope.$watch "#{formName}.$pristine", (pristine) =>
@unsaved = !pristine
@saved = false unless pristine
scope.$watch "#{formName}.$valid", (valid) =>
@setValid(valid)
ngForm: => @scope[@formName]
setValid: (valid) =>
@valid = valid
@invalid = !valid
setUnsaved: =>
@saved = false
@unsaved = true
@ngForm.$setDirty()
onRemoteSuccess: =>
@clearNetworkState()
@saved = true
@unsaved = false
@ngForm().$setPristine()
onRemoteError: =>
@clearNetworkState()
@unsaved = true
# can assign errors from server here
delete @object().errors
@setValid(false)
onNetworkError: (error) =>
@submitting = false
@submitError = "#{error.status} error"
clearNetworkState: =>
@submitting = false
@submitError = false
FormHelper
]
@TylerRick
Copy link

This looks like an interesting/useful pattern. Do you have an example handy showing how you might integrate it with a controller?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment