根据AngularJS变量改变DOM元素类型
问题描述:
我试图取决于一个范围变量的DOM元素将改变类型实现..根据AngularJS变量改变DOM元素类型
所以说我有一个像范围VAR:
$scope.post = {
title: 'Post title goes here!',
slug: 'post-title-goes-here',
category: 'News',
featured_image: '//src.jpg'
};
和DOM元素,如:
<a href="#/post/{{post.slug}}">
<div style="background-image: url({{post.featured_image}});">
<small ng-if="post.category">{{post.category}}</small>
<h3>{{post.title}}</h3>
</div>
</a>
但是,如果VAR $scope.post.slug
是空的DOM元素看起来像:
<div>
<div style="background-image: url({{post.featured_image}});">
<small ng-if="post.category">{{post.category}}</small>
<h3>{{post.title}}</h3>
</div>
</div>
很明显,我可以做一个ng-if
并复制每一点代码,但我试图避免这一点!
像这样的理想:
<{{post.slug ? 'a href="#/post/'+post.slug+'"' : 'div'}}>
<div style="background-image: url({{post.featured_image}});">
<small ng-if="post.category">{{post.category}}</small>
<h3>{{post.title}}</h3>
</div>
</{{post.slug ? 'a' : 'div'}}>
答
我不认为你可以直接与角度实现这一目标。 HTML需要在角度注入之前定义。但是对于这种情况,我认为使用控制器逻辑中的函数控制锚点更好。只需使用div和ng-click ='yourFunction()'设置您的DOM,并在存在post.slug的情况下,使用角度路由系统进行导航。
答
自定义指令将允许您执行ng-if来确定<a>
标记或<div>
标记而不污染您的视图。指令中的ngTransclude包含您的内容。
查看:
<div ng-repeat="post in posts">
<div slug-link="post.slug">
<div style="background-image: url({{post.featured_image}});">
<small ng-if="post.category">{{post.category}}</small>
<h3>{{post.title}}</h3>
</div>
</div>
</div>
指令:
.directive('slugLink', function()
{
return {
transclude: true,
scope: {
slug: '=slugLink'
},
template: '<a ng-href="{{slug}}" ng-if="slug" ng-transclude></a><div ng-if="slug == \'\'" ng-transclude></div>'
};
});
查看完整的源在Plunkr
的条件是两个'NG-if's相同... –
你”再右吧。修正并更新了这一点。我正在用几种不同的方式来做这个检查。 OP可以编辑这些值以匹配他拥有的数据。 – AndrewR