【问题标题】:Hide an attribute with ng-hide使用 ng-hide 隐藏属性
【发布时间】:2015-02-03 22:00:39
【问题描述】:

我正在使用输入字段值属性来显示用户在我的应用的 SERP 上输入的查询。我想隐藏在结果未定义的页面上查询的值。是否可以使用 ng-show 来隐藏一个属性而不是整个元素?

翡翠

    div(ng-controller="SearchCtrl", class="header-search-form")
      form(id="search-form-homepage" class="input-group input-lg")
        input(type="search",
        ng-enter="doSearch(query.term)",
        ng-hide="query.term === 'undefined'",
        ng-model="query.term",
        class="form-control header-search-result",
        value="#{data.query}")

【问题讨论】:

  • 我不知道你在说什么,但我不这么认为。这在 HTML 中会是什么样子?我什至不明白您所说的“隐藏属性”是什么意思。 Angular 只是创建 HTML,所以如果它不是你可以用 HTML 做的事情,那就不行。听起来您有一个与页面一起加载的query.term 值,如果它未定义,您不想显示它,但您仍然希望用户能够键入内容?当您设置该值时,您可能应该将其清除。
  • 好吧,我理解尝试删除属性值的困惑。在 HTML 中,这会完全删除输入元素。
  • 一定是关于 Jade 的东西,我没有看到任何关于占位符的东西...

标签: angularjs angularjs-directive pug


【解决方案1】:

您必须为此任务创建自己的指令。作为example - plnkr,我创建了一个将删除占位符属性的指令。

注意这里的关键区别是我们不能“隐藏”属性,因为 hide 真的是

display: 0; 

我们可以删除或添加它们。

app.directive('attrHide', function(){
  return {
    restrict: 'A',
    scope: {
      attrHide: '='
    },
    link: function(scope, elm, attr){
      var targetAttr = attr.hiddenAttribute;
      var saveAttr = attr[targetAttr] || '';

      scope.$watch('attrHide', function(newVal){
        if (newVal){
          elm.removeAttr(targetAttr);
        } else {
          elm.attr(targetAttr,saveAttr);
        }
      })
    }
  }
})

在标记中你可以有

<input  ng-model="target"/>
<input placeholder="hello" hidden-attribute="placeholder" attr-hide="target=='hello'"/>

这里在attr-hide里可以放真假表达式,在hidden-attribute里可以选择要移除的属性

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多