从angular js升级到angular 8的指令

问题描述 投票:0回答:1

某人可以帮助将该指令升级到有角度的2 +

我喜欢这个指令,因为我只能验证float,因此也可以复制粘贴数据或将数据放入其中]

var myApp = angular.module('myApp', ['ngStorage']);
myApp.controller('MyCtrl', ['$scope', function($scope) {

}]).directive('floatOnly', function() {
  return {
    require: 'ngModel',
    restrict: 'A',
    link: function(scope, element, attrs, modelCtrl) {
      modelCtrl.$parsers.push(function(inputValue) {
        if (inputValue === undefined) return '';

        // Remove forbidden characters
        cleanInputValue = inputValue.replace(',', '.') // change commas to dots
          .replace(/[^\d.]/g, '') // keep numbers and dots
          .replace(/\./, "x") // change the first dot in X
          .replace(/\./g, "") // remove all dots
          .replace(/x/, "."); // change X to dot
        if (cleanInputValue != inputValue) {
          modelCtrl.$setViewValue(cleanInputValue);
          modelCtrl.$render();
        }
        return cleanInputValue;
      });
    }
  }
});

jsfiddle example

有人可以帮助将该指令升级到有角度的2+,我喜欢这个指令,因为我只能验证float,也可以复制粘贴数据或将数据放入其中var myApp = angular.module('...] >

angularjs angular angularjs-directive angular2-directives angular-upgrade
1个回答
0
投票

尝试一下:WORKING DEMO

import { Directive, Renderer2, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[float-only]'
})
export class FloatOnlyDirective{
  constructor(private elem: ElementRef, private render: Renderer2) {  }
  @HostListener('input')
  onChange() {
    let value = this.elem.nativeElement.value.replace(',', '.') 
          .replace(/[^\d.]/g, '') // keep numbers and dots
          .replace(/\./, "x") // change the first dot in X
          .replace(/\./g, "") // remove all dots
          .replace(/x/, ".") ;
    this.elem.nativeElement.value = value;
  }

}
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.