AngularJS <input> 类型设置为“数字”,如何强制将初始值显示为非数字字符串

Posted

技术标签:

【中文标题】AngularJS <input> 类型设置为“数字”,如何强制将初始值显示为非数字字符串【英文标题】:AngularJS <input> with type set to 'number', how to force a initial display of value to a non-number string 【发布时间】:2015-10-28 13:21:39 【问题描述】:

我想知道使用 Angular,如果 &lt;input&gt; 将“类型”设置为“数字”,如果 ng-model 初始化为某个数字(在我的示例中为 0),您能否强制初始显示非数字字符串)?

我的示例代码在这里:http://plnkr.co/edit/TwraJlxZSd3TeSYscExq?p=info

本主题与: [1]: 'AngularJS directives to hide zero when <input> is initially loaded to the DOM'

和: [2]: 'Hide Value in input when it's zero in angular Js'

【问题讨论】:

我不这么认为。我遇到了类似的问题,我的解决方案是将字符串解析为整数。 请将你的代码带入问题本身,这样以后的人,如果“plnkr”死掉(或只是暂时摔倒),仍然可以看到相关代码,理解问题并学习答案。我们只需要minimal code 即可可视化和重现您的问题。 placeholder="-"怎么样? 这是一种解决方法。谢谢 【参考方案1】:
The following directive will solve your problem,


app.directive('hideZero', function() 
    return 
      link: function(scope, element, attrs) 
        var modelName = attrs.ngModel;
        scope.$watch(modelName, function(newVal, oldVal)
          if(newVal === 0) 
            element[0].value = null;
            scope[modelName] = null;
          
        );
      
    ;
)

【讨论】:

以上是关于AngularJS <input> 类型设置为“数字”,如何强制将初始值显示为非数字字符串的主要内容,如果未能解决你的问题,请参考以下文章

ionic angularJS input 相关指令 以及定时器 的使用

AngularJS <input> 类型设置为“数字”,如何强制将初始值显示为非数字字符串

AngularJS ng-keydown 指令仅适用于 <input> 上下文?

angularjs 自定义指令控制input只能输入数字和字母

如何使用angularjs实现按钮事件

AngularJS 控制器