【问题标题】:how to hide value of input element if its $pristine如果输入元素的$原始值,如何隐藏它的值
【发布时间】:2015-11-29 16:04:32
【问题描述】:

我已将 ng-model 附加到 ,但如果未触摸它,我想显示默认占位符值 ($pristine)。有什么好的方法吗?我不能在初始时简单地将我的 ng-model 值设置为 null。 这是我的笨蛋: http://plnkr.co/edit/0kzKrwKTbJzsMGG8D1gQ?p=preview

<body ng-controller="inputController">
    <input type="number" id="pricefield" min="0" name="price" placeholder="Price" ng-model="test.value" required/>

</body>

angular.module('plunker', []);
function inputController($scope) {
  $scope.test = {value: 0};
}

【问题讨论】:

    标签: angularjs forms validation input angularjs-forms


    【解决方案1】:

    您可以使用ng-attr 指令动态设置占位符值,以检查表单元素是否为pristine,您需要将此字段放在form 中,然后您可以轻松检查$pristine 的属性像myForm.price.$pristine 这样的表单元素。

    标记

    <form name="myForm">
      <input type="number" id="pricefield" min="0" name="price" ng-model="test.value" 
       ng-attr-placeholder="{{myForm.price.$pristine ? 'Some Value': 'Default Value'}}" required/>
    </form>
    

    Demo Plunkr

    更新

    我建议使用一个指令来更改在初始加载时隐藏$viewValue 并显示占位符。指令将在 ngModelControlller 上使用 $formatters 控制显示值

    标记

    <input type="number" custom-dir id="pricefield" min="0" name="price" 
    ng-attr-placeholder="{{myForm.price.$pristine ? 'Initial Placeholder': 'After change Placeholder'}}" 
    ng-model="test.value" required/>
    

    指令

    app.directive('hideInitialLoad', function() {
      return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {
          var initalHide = true;
          //format text going to user (model to view)
          ngModel.$formatters.push(function(value) {
            console.log(attr.min > value)
            if (initalHide){
              initalHide = false;
              return undefined;
            }
            return value;
          });
        }
      };
    });
    

    Updated Demo

    【讨论】:

    • 嗨,@Pankaj Parkar,谢谢。但是,我需要在初始化期间将 ng-model 设置为 0,如果我这样做,这将无法正常工作。 (隐藏初始值,显示占位符)
    • @WABBIT0111 你能设置min="1"..会工作plnkr.co/edit/DzC5XyzXCmAGhTJgROCk?p=preview
    • @WABBIT0111 很高兴为您提供帮助..谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    相关资源
    最近更新 更多