angularjs - 如果被包含的内容为空,如何隐藏元素?

标签 angularjs angularjs-directive transclusion

我创建了一个非常简单的指令,该指令显示键/值对。如果所包含的内容为空(长度为零或只是空白),我希望能够自动隐藏该元素。

我无法弄清楚如何访问在指令中被包含的内容。

app.directive('pair', function($compile) {
  return {
    replace: true,
    restrict: 'E',
    scope: {
      label: '@'
    },
    transclude: true,
    template: "<div><span>{{label}}</span><span ng-transclude></span></div>"
  }
});

例如,我希望显示以下元素。
<pair label="My Label">Hi there</pair>

但是接下来的两个元素应该被隐藏,因为它们不包含任何文本内容。
<pair label="My Label"></pair>
<pair label="My Label"><i></i></pair>

我是Angular的新手,所以也许可以采用一种很好的方法来解决此类问题。任何帮助表示赞赏。

最佳答案

这是一种在模板上和ng-show中使用compile transcludeFn的方法,用于检查所包含的html是否具有文本长度。

如果未将文字长度ng-show设置为隐藏

app.directive('pair', function($timeout) {
  return {
    replace: true,
    restrict: 'E',
    scope: {
      label: '@'
    },
    transclude: true,
    template: "<div ng-show='1'><span>{{label}} </span><span ng-transclude></span></div>",
    compile: function(elem, attrs, transcludeFn) {
            transcludeFn(elem, function(clone) { 
              /* clone is element containing html that will be transcludded*/
               var show=clone.text().length?'1':'0'
                attrs.ngShow=show;
            });
        }
  }
});

Plunker demo

关于angularjs - 如果被包含的内容为空,如何隐藏元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15768517/

相关文章:

javascript - Angular 的动态属性

javascript - 简单的登录系统UserController

javascript - ng-if 和 ng-class-even/odd 不能很好地协同工作并且不会得到预期的结果

angularjs - 在 Angular.JS 中缓存 DOM

javascript - 让 angular-masonry 工作它说它没有方法 'imagesLoaded'

javascript - Angular : How to create a transcluding element directive that keeps attribute directives and can add new ones?

angularjs - 将数据从重复组件传递到嵌入的重复元素

angularjs-scope - 结合 ng-repeat 和指令拒绝嵌入的内容访问外部范围?

javascript - 从另一个 Controller Angularjs 调用函数

javascript - MongoDB |无法更新文档的 'role'