Last active
March 22, 2016 20:20
-
-
Save ragingprodigy/907b02abdaea59a4b8c9 to your computer and use it in GitHub Desktop.
Script to set the value of an input field populated using a browser's autocomplete feature
This file contains hidden or 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 'myModule', [] | |
.factory 'inputsWatcher', ( $interval ) -> | |
INTERVAL_MS = 500 | |
handlers = [] | |
execHandlers = -> | |
for handler in handlers | |
handler() | |
registerInput: (handler) -> | |
if handlers.push handler | |
$interval execHandlers, INTERVAL_MS | |
unregisterInput: (handler) -> | |
handlers.splice handlers.indexOf(handler), 1 | |
if handlers.length is 0 then $interval.cancel promise | |
.config ($provide) -> | |
inputDecoration = ($delegate, inputsWatcher) -> | |
directive = $delegate[0] | |
link = directive.link | |
handler = null | |
linkDecoration = (scope, element, attrs, ngModel) -> | |
# By default model.$viewValue is equals to undefined | |
if attrs.type is "checkbox" | |
handler = -> | |
value = element[0].checked | |
# By default element is not checked | |
if value and ngModel.$viewValue isnt value then ngModel.$setViewValue value | |
else if attrs.type is "radio" | |
handler = -> | |
value = attrs.value | |
# By default element is not checked | |
if element[0].checked and ngModel.$viewValue isnt value then ngModel.$setViewValue value | |
else | |
handler = -> | |
value = element.val() | |
# By default value is an empty string | |
if (ngModel.$viewValue isnt undefined or value isnt "") and ngModel.$viewValue isnt value then ngModel.$setViewValue value | |
inputsWatcher.registerInput handler | |
scope.$on "$destroy", -> | |
inputsWatcher.unregisterInput handler | |
# Exec original `link()` | |
link.$apply this, [].slice.call(arguments, 0) | |
# Decorate `link()` don't work for `inputDirective` (why?) | |
# directive.link = linkDecoration; | |
# So use `compile()` instead | |
directive.compile = (element, attrs, transclude) -> | |
linkDecoration | |
delete directive.link | |
$delegate | |
$provide.decorator "inputDirective", inputDecoration | |
$provide.decorator "textareaDirective", inputDecoration |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment