【问题标题】:Upgrade directive from angular js to angular 8从 Angular js 升级到 Angular 8 的指令
【发布时间】:2020-04-01 15:38:33
【问题描述】:

有人可以帮助将此指令升级为 angular 2+

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

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

【问题讨论】:

    标签: angularjs angular angularjs-directive angular2-directives angular-upgrade


    【解决方案1】:

    试试这个: 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;
      }
    
    }
    

    您也可以使用Renderer2 更新innerHtml。这样会更干净,

    祝您的 Angular 之旅万事如意!!

    【讨论】:

      猜你喜欢
      • 2020-05-16
      • 1970-01-01
      • 2019-11-30
      • 2019-10-26
      • 2019-11-07
      • 1970-01-01
      • 2020-03-21
      • 2020-01-20
      • 2023-03-18
      相关资源
      最近更新 更多