Javascript 根据AngularJS变量更改DOM元素类型
我试图实现的是DOM元素将改变类型的范围变量 假设我有一个范围变量,比如:Javascript 根据AngularJS变量更改DOM元素类型,javascript,jquery,angularjs,dom,Javascript,Jquery,Angularjs,Dom,我试图实现的是DOM元素将改变类型的范围变量 假设我有一个范围变量,比如: $scope.post = { title: 'Post title goes here!', slug: 'post-title-goes-here', category: 'News', featured_image: '//src.jpg' }; 和一个DOM元素,如: <a href="#/post/{{post.slug}
$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>
显然,我可以做一个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'}}>
{{post.category}
{{post.title}
我认为你不能直接用angular实现这一点。需要在角度注入之前定义HTML。但是对于这种情况,我认为使用控制器逻辑中的函数来控制锚点是一个更好的选择。只需使用div和ng click='yourFunction()'设置DOM,如果存在post.slug,则使用angular的路由系统进行导航自定义指令将允许您执行ng if's以确定'
};
});
请参阅中的完整源代码,您是对的。修正并更新了。我在胡思乱想用几种不同的方法来检查。OP可以编辑这些值以匹配他拥有的数据。
<{{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'}}>
<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>'
};
});