基本上,我在我的模板中有这个代码:
<tr ng-repeat="entry in tableEntries">
<td ng-switch="entry.url == ''">
<span ng-switch-when="false"><a href="{{entry.url}}">{{entry.school}}</a></span>
<span ng-switch-when="true">{{entry.school}}</span>
</td>
...
</tr>
正如您所看到的,我正在尝试在entry.url
不为空时显示可点击的URL,否则显示纯文本。它工作正常,但看起来很丑陋。有更优雅的解决方案吗?
我能想到的另一种方法是使用ng-if
:
<td>
<span ng-if="entry.url != ''"><a href="{{entry.url}}">{{entry.school}}</a></span>
<span ng-if="entry.url == ''">{{entry.school}}</span>
</td>
然而,我会两次重复几乎相同的比较,这看起来更糟。你们怎么会接近这个?
答案 0 :(得分:5)
你可以试试。
<div ng-show="!link">hello</div>
<div ng-show="!!link"><a href="{{link}}">hello</a></div>
但是你使用的ngSwitch
应该没问题。
答案 1 :(得分:2)
使用双重否定,它会转换为布尔值,因此如果字符串不为空,!!entry.url
将返回true
。
<td ng-switch="!!entry.url">
<span ng-switch-when="true"><a href="{{entry.url}}">{{entry.school}}</a></span>
<span ng-switch-when="false">{{entry.school}}</span>
</td>
好的阅读What is the !! (not not) operator in JavaScript?和Double negation (!!) in javascript - what is the purpose?
答案 2 :(得分:2)
您可以创建一个隐藏复杂性的自定义指令:
<强> HTML 强>
<tr ng-repeat="entry in tableEntries">
<td>
<link model="entry"></link>
</td>
...
</tr>
<强> JS 强>
app.directive('link', function() {
return {
restrict: 'E',
scope: {
model: '='
},
template: '<a ng-if="model.url != ''" href="{{model.url}}">{{model.school}}</a><span ng-if="model.url == ''"> {{ model.school }}</span>'
}
});
答案 3 :(得分:-1)
我建议你的td中有一个ng-class =“{'className':whenEntryURLisWhatever}”,并让它改变所访问的css样式,例如:
td span{ /*#normal styles#*/ }
.className span{ /*#styles in the case of added classname (when it is a link)#*/
text-decoration: underline;
cursor: pointer;
}
然后只需更改javascript代码中定义的函数中ng-click所发生的情况。
$scope.yourFunction = function(url){
if(!!url){
window.location = YourURL;
}
}
这会减少代码重复,因为你的html现在可能是:
<tr ng-repeat="entry in tableEntries">
<td ng-class="{'className': !!entry.url}">
<span ng-click="yourFunction(entry.url)">{{entry.school}}</span>
</td>
...
</tr>