import {module} from '../module'; import Component from '../lib/component'; import * as resolveFactory from '../lib/resolveDefaultComponents'; import * as normalizerFactory from '../lib/inputAttrsNormalizer'; import './style.scss'; import './index.mdl'; export default class Textfield extends Component { constructor($element, $scope, $attrs) { super($element); let input = this.input = this.element.querySelector('input'); input.addEventListener('input', () => this.checkValue()); input.addEventListener('focus', () => this.checkValue()); input.addEventListener('blur', () => this.showClear(false)); let clearButton = this.element.querySelector('button'); clearButton.addEventListener('click', () => this.onClearClick()); clearButton.addEventListener('mousedown', event => event.preventDefault()); let div = this.element.firstChild; componentHandler.upgradeElement(div); } link($scope, $attrs) { let mdlTextField = this.element.firstChild.MaterialTextfield; mdlTextField.updateClasses_(); $scope.$watch($attrs.model, () => mdlTextField.updateClasses_()); } onClearClick() { this.input.value = ''; this.checkValue(); let event = this.document.createEvent('HTMLEvents'); event.initEvent('change', false, true); this.input.dispatchEvent(event); } checkValue() { this.showClear(this.input.value); } showClear(show) { show = document.activeElement === this.input; let clearButton = this.element.querySelector('button'); clearButton.style.visibility = show ? 'visible' : 'hidden'; } /** * Selects the textfield. */ select() { this.input.select(); } /** * Puts the focus on the textfield. */ focus() { this.input.focus(); } } Textfield.$inject = ['$element', '$scope', '$attrs']; directive.$inject = [resolveFactory.NAME, normalizerFactory.NAME]; export function directive(resolve, normalizer) { return { restrict: 'E', template: function(_, attrs) { normalizer.normalize(attrs); return resolve.getTemplate('textfield', attrs); }, link: function($scope, $element, $attrs, $ctrl) { $ctrl.link($scope, $attrs); }, controller: Textfield }; } module.directive('vnTextfield', directive);