【问题标题】:How can i binding string length zero-value in angularjs?如何在angularjs中绑定字符串长度零值?
【发布时间】:2014-10-06 14:23:07
【问题描述】:

我需要表达字符串长度。 所以,我就是这么做的。

<div>
<input type='text' ng-model="inputValue">
<span>Your input key count : {{inputValue.length}}</span>
<div>

结果。
没有输入 => "" (空)
一些键输入 => 1 或 2 或 3(正确的长度)

我认为没有显示长度 0 值。
但我需要零值。这个怎么显示?

【问题讨论】:

    标签: javascript angularjs binding


    【解决方案1】:

    当变量的长度为“0”时,在视图中显示“0”的最佳方法或理想方法是使用.toString()

    就像你的情况一样,答案可能是:

    <div>
    <input type='text' ng-model="inputValue">
    <span>Your input key count : {{inputValue.length.toString()}}</span>
    <div>
    

    【讨论】:

      【解决方案2】:

      JSfiddle

      控制器:

          $scope.inputValue = "";
      

      HTML:

       <div>
                      <input type='text' ng-model="inputValue">
                      <span>Your input key count : {{inputValue.length}}</span>
                  </div>
      

      【讨论】:

      • 我正要添加这个作为答案......很好地创造了你可以使用的小提琴:) jsfiddle.net/hgao0h1h
      【解决方案3】:

      如果您不想关心初始化,请执行以下操作:

      <div>
        <input type='text' ng-model="inputValue" >
        <span>Your input key count : {{inputValue ? inputValue.length : 0}}</span>
      <div>
      

      【讨论】:

      • 这个解决方案并不理想。考虑到这一点,inputValue 也可以是一个函数,它返回一个数组值作为输出,你必须得到它的length。您可以使用ngInit,也可以多次调用该函数;一次检查它是否返回任何值,或者第二次获取它的长度。这样它就可以多次运行该功能。
      • 对此,我在下面提供了一个解决方案。 click here
      【解决方案4】:

      您应该使用空字符串初始化 inputValue。您可以通过添加 ng-init 来做到这一点

      <div>
        <input type='text' ng-model="inputValue" ng-init="inputValue=''">
        <span>Your input key count : {{inputValue.length}}</span>
      <div>
      

      【讨论】:

      • 您可能需要在ng-init 仔细检查您的撇号。
      猜你喜欢
      • 2018-12-26
      • 2019-09-25
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      相关资源
      最近更新 更多