Last active
December 17, 2015 19:09
-
-
Save glebm/5658158 to your computer and use it in GitHub Desktop.
AngularJS Form Helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks like an interesting/useful pattern. Do you have an example handy showing how you might integrate it with a controller?