我创建了一个非常简单的指令,该指令显示键/值对。如果所包含的内容为空(长度为零或只是空白),我希望能够自动隐藏该元素。
我无法弄清楚如何访问在指令中被包含的内容。
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/