使用AngularJS,我希望能够有条件地呈现包含内容的HTML元素或仅包含该HTML元素的内容。例如,我想要在某些文本周围呈现<a>
标记,或者根据某些条件呈现文本:
HTML标记逻辑
<!-- If model.hasMoreInfo (a bool value) is true, render link and text -->
<a href="/moreinfo">{{model.label}}</a>
<!-- otherwise just render text -->
{{model.label}}
$范围模型示例
$scope.model = {
hasMoreInfo: true,
label: 'My Label'
};
我想避免在不需要的时候用其他“容器”HTML元素(如<span>
)包装文本。
答案 0 :(得分:3)
我提出的解决方案是一个自定义指令,它使用 ng-if 类型的逻辑/模式,我可以将其作为属性应用于元素(在立即调用函数):
AngularJS指令
(function () {
var directiveId = 'renderWrapIf';
var directive = function() {
return {
link: function($scope, element, attributes) {
$scope.$watch(attributes[directiveId], function ngIfWatchAction(value) {
if (!value) {
element.replaceWith(element.contents());
}
});
}
};
};
angular.module('app').directive(directiveId, directive);
})();
标记用法
<a render-wrap-if="model.hasMoreInfo" href="/moreinfo">{{model.label}}</a>
真实时渲染结果
<a render-wrap-if="model.hasMoreInfo" href="/moreinfo" class="ng-binding">My Label</a>
虚假时呈现结果
My Label
这允许我以一种仍然熟悉且易于识别预期渲染的形式创建标记,但也能够避免整个“容器”额外标记,以使某些数据绑定逻辑工作。我也可以将此指令用于其他元素,而不仅仅是<a>
标签等。