问题
I'm trying to create a menu using angular. A menu item can have children requiring another ng-repeat to print the sub nav items. I'm noticing some strange behavior when attempting to insert an anchor tag within the 2nd ng-repeat.
Link to fiddle: http://jsfiddle.net/npU7t/
<li ng-repeat="sub_menu_item in menu_item.sub_menu">
<a href="">
{{ sub_menu_item.title }}
</a>
</li>
With
{
title: 'menu item with children',
sub_menu: [
{
title: '<-- empty anchor tag???'
}
]
}
Results in
<li ng-repeat="sub_menu_item in menu_item.sub_menu" class="ng-scope">
<a href=""></a>
<a href="" class="ng-binding"><-- empty anchor tag???</a>
</li>
Where the did duplicate / empty anchor tag come from? How can I prevent it from being created?
Appreciate the help!
回答1:
This isn't a bug with Angular, but rather how you have your markup.
UPDATE:
The issue is actually the nested <a>
tag, not the <ul>
tag.
<a href="">
<span class="title">{{ menu_item.title }}</span>
<ul class="sub-menu" ng-if="menu_item.sub_menu">
<li ng-repeat="sub_menu_item in menu_item.sub_menu">
<a href="">
{{ sub_menu_item.title }}
</a>
</li>
</ul>
</a>
In fact, if you remove Angular from the equation altogether, you will see that the extraneous <a>
tag is still added to the DOM: http://jsfiddle.net/jwcarroll/cXkj4/
If you get rid of the nested <a>
tag, then the extra element will disappear.
<a href="">
<span class="title">{{ menu_item.title }}</span>
</a>
<ul class="sub-menu" ng-if="menu_item.sub_menu">
<li ng-repeat="sub_menu_item in menu_item.sub_menu">
<a href="">
{{ sub_menu_item.title }}
</a>
</li>
</ul>
In both HTML 4.01, and HTML 5, having a nested <a>
tag is a no no.
The simplest possible recreation of the problem I could come up with is this bit of markup:
<a href="">Outer
<p>Blah
<a href="">Inner</a>
</p>
</a>
Because you can't nest <a>
elements within each other, the browser is doing it's best to recreate your intent while keeping the DOM clean. What you end up with is this:
<a href="">Outer</a>
<p>
<a href="">Blah</a>
<a href="">Inner</a>
</p>
This makes sense when you realize what the browser is trying to do. The browser is trying to do three things:
- Keep
Outer
,Blah
andInner
text elements inside hyperlinks - Contain
Blah
and<a>Inner</a>
inside a single<p>
tag - Ensure no
<a>
tags are nested within each other
The only sensible way to accomplish all three of these is to wrap both Outer
and Blah
text elements in separate <a>
tags in a way that isn't nested. This is the closest approximation to the original intent without breaking the DOCTYPE rules.
I hope this helps.
回答2:
Very strange. It doesn't appear with any tag besides <a>
(like <p>
or <div>
). It looks like an outright bug to me - I'd submit a proper bug report.
来源:https://stackoverflow.com/questions/24153850/ng-repeat-inserting-empty-anchor-tags