Skip to content

Instantly share code, notes, and snippets.

@Androguide
Created July 11, 2014 11:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Androguide/d0e7f5874a9b65569312 to your computer and use it in GitHub Desktop.
Save Androguide/d0e7f5874a9b65569312 to your computer and use it in GitHub Desktop.
A directive providing native AngularJS 2-way data-binding support for Polymer's <paper-input> component
'use strict';
// Paper Input Directive
// ---------------------
// The AngularJS directive allowing to bind to Polymer's `<paper-input>` elements
// with Angular like they were standard HTML5 `<input>` elements, using the `ng-model` attribute
angular.module('Androguide').directive('paperInput', ['$parse', '$timeout', '$browser', function ($parse, $timeout, $browser) {
return {
restrict: 'E',
require: '?ngModel',
link: function postLink(scope, element, attrs) {
var input = element[0];
if (attrs.ngModel) {
bindNgModel('ngModel', 'inputValue');
}
function bindNgModel(attrName, inputName) {
var ngModelGet = $parse(attrs[attrName]);
toInput(ngModelGet, attrs[attrName], inputName);
toModel(ngModelGet, attrs[attrName], inputName);
}
function toInput(ngModelGet, attrName, inputName) {
$timeout(function () {
input[inputName] = ngModelGet(scope);
}, 350);
var first = true;
scope.$watch(attrName, function ngModelWatch() {
if (first) {
first = false;
return;
}
input[inputName] = ngModelGet(scope);
});
}
function toModel(modelGet) {
var ngModelSet = modelGet.assign;
var timeout;
var deferListener = function (ev) {
if (!timeout) {
timeout = $browser.defer(function () {
listener(ev);
timeout = null;
});
}
};
var listener = function (event) {
ngModelSet(scope, input.inputValue);
scope.$apply();
};
input.addEventListener('change', function (event) {
deferListener(event);
});
input.addEventListener('keydown', function (event) {
var key = event.keyCode;
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener(event);
});
}
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment