Created
September 14, 2015 18:49
-
-
Save voznik/c8bd8333bb21ec99b8c7 to your computer and use it in GitHub Desktop.
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
@directive = angular.module('ui-commons.autosave', []) | |
@directive.directive 'autosave', ['formHandler', 'promiseTrackers', '$timeout', (formHandler, promiseTrackers, $timeout) -> | |
restrict: 'A' | |
require: ['form', 'autosave'] | |
controller: ($scope) -> | |
submitExpr = null | |
tracker = null | |
currentPromise = null | |
formDelay = null | |
validate = null | |
@init = (formCtrl, expr, trackerName, validating, delay) -> | |
submitExpr = expr | |
tracker = promiseTrackers(trackerName || formCtrl.$name) | |
validate = validating || false | |
form = formCtrl | |
formDelay = delay || 1000 | |
@withTimeout = (fn, delay) -> | |
if currentPromise | |
$timeout.cancel currentPromise | |
currentPromise = $timeout fn, delay || formDelay | |
@submit = (properties) -> | |
tracker.addPromise (() -> | |
if validate | |
formHandler.validate $scope[form.$name], () -> | |
$scope.$eval submitExpr, $changes: properties | |
else | |
$scope.$eval submitExpr, $changes: properties | |
)() | |
@ | |
compile: (cElement, cAttributes, transclude) -> | |
pre: (scope, formElement, attr, ctrls) -> | |
ctrls[1].init ctrls[0], attr.ngSubmit, scope.$eval(attr.autosave), scope.$eval(attr.autosaveValidate), attr.autosaveDelay | |
return | |
] | |
getRestrictedAutosaveDirective = (restriction) -> | |
autoSaveFieldDirective = [() -> | |
restrict: restriction | |
require: ['?ngModel', '^?autosave'] | |
compile: (cElement, cAttributes, transclude) -> | |
pre: (scope, input, attr, ctrls) -> | |
if ctrls[1] && !attr.autosaveNone | |
autosave = (changes) -> | |
ctrls[1].withTimeout () -> | |
ctrls[1].submit(changes) | |
, attr.autosaveDelay | |
if ctrls[0] | |
scope.$watch attr.ngModel, (newVal, oldVal) -> | |
if newVal && !angular.equals(newVal, oldVal) && ctrls[0].$dirty | |
autosave([attr.ngModel]) | |
else | |
input.on 'change', (e) -> | |
autosave(input.attr('name')) | |
return | |
] | |
@directive.directive 'input', getRestrictedAutosaveDirective('E') | |
@directive.directive 'textarea', getRestrictedAutosaveDirective('E') | |
@directive.directive 'select', getRestrictedAutosaveDirective('E') | |
@directive.directive 'checkbox', getRestrictedAutosaveDirective('E') | |
@directive.directive 'radio', getRestrictedAutosaveDirective('E') | |
@directive.directive 'autosaveField', getRestrictedAutosaveDirective('A') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment