【问题标题】:rendering a dynamic placeholder with angular使用角度渲染动态占位符
【发布时间】:2014-04-23 14:04:22
【问题描述】:

我环顾四周,发现了几个标记为“ng-placeholder”或类似的资源。我无法让它工作:

<input type="text" placeholder="{{option.name}}" class="form-control" ng-switch-when="text" />

我注意到input documentation 上似乎也没有任何内容。我对角度很陌生,这只会让我沮丧几个小时。一定有办法做到这一点。

【问题讨论】:

  • 也许您可以使用ng-bind 将当前输入占位符替换为{{ option.name }}。只是一个想法。 ;-)
  • @FaizShukri 我试过了。出于某种原因,ng-bind 在输入标签本身中放入了一些数据(例如 [Object object]),因此我觉得这不是正确的做法。跨度>

标签: javascript angularjs placeholder


【解决方案1】:

为什么不为 ng-placeholder 编写自己的指令呢?像这样简单的东西应该可以工作。你可以像这样在你的html中调用它

<input ng-placeholder='test'>

其中 test 是当前控制器中的范围变量。

.directive('ngPlaceholder', function($document) {
  return {
    restrict: 'A',
    scope: {
      placeholder: '=ngPlaceholder'
    },
    link: function(scope, elem, attr) {
      scope.$watch('placeholder',function() {
        elem[0].placeholder = scope.placeholder;
      });
    }
  }
});

【讨论】:

  • 如果它看起来不那么神秘,我会这样做。除此之外,即使传入测试字符串,我似乎也无法定义(所以它可以工作,只是不正确,似乎?)。有什么我想念的吗?我所做的是通过“myApp.directive('...' ...)”将其附加到我的根模块
  • @Seiyria 这很奇怪,似乎对我很有用。这是JSFiddle
  • 哦,我明白了。我花了一点时间才意识到这是一个变量,而不是字符串。我仍然习惯于在某些情况下(例如单选按钮)对需要表示为字符串(例如“'String'”)的数据进行双引号。谢谢!
【解决方案2】:

AngularJS中存在条件属性属性ng-attr-{property_name}

例如,我对不同的搜索词使用不同的占位符

 ng-attr-placeholder="{{isAdvanceSearch ? setPlaceholder(searchOption) : 'John Smith, 08/23/1970, 123'}}"

这里基于isAdvanceSearch变量,我在setPlaceholder方法中设置了不同的占位符。

setPlaceholder 方法返回要在输入字段中设置的占位符。

$scope.setPlaceholder = function(searchOption) {
     if (searchOption === "foo") {
          return "Search by foo… e.g. foo1";
     } else if (searchOption === "bar") {
          return "Search by bar… e.g. bar123";
     } else {
          return "John Smith, 08/23/1970, 123";
     }
};

注意:John Smith, 08/23/1970, 123 是默认占位符。 不要忘记将表达式括在 {{}} 括号中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-25
    • 2017-12-31
    • 2021-05-21
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多