有条件地以角度显示链接.js
Displaying link conditionally in Angular.js
基本上,我的模板中有以下代码:
<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>
但是,我会重复两次几乎相同的比较,这看起来更糟。你们会如何处理这个问题?
你可以试试。
<div ng-show="!link">hello</div>
<div ng-show="!!link"><a href="{{link}}">hello</a></div>
但是您正在使用的ngSwitch
应该没问题。
使用双否定,它转换为布尔值,因此如果字符串不为空!!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>
好好读懂的是什么!!(不是不是)JavaScript 中的运算符?和 javascript 中的双重否定 (!!) - 目的是什么?
您可以创建一个隐藏复杂性的自定义指令:
.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>'
}
});
我建议在你的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>
相关文章:
- Jquery在初始页面加载时选中复选框时显示链接的代码
- 当主导航链接悬停时,在侧菜单中显示链接
- 悬停时无法单击锚标记,但其显示链接
- 如何通过mailto在电子邮件中突出显示链接
- 如何在第一次点击时突出显示链接;并在第二次单击时跟随它,除非在其他地方单击,然后重新初始化未高亮显示的状态
- 希望仅为已登录的用户显示链接,否则它显示该链接在AngularJS和NodeJS中被隐藏或禁用
- 点击提交按钮后如何显示链接
- 如何使用 JavaScript 在共享按钮中显示链接
- 如何制作一个按钮,当悬停在上面时,会滑动并显示链接 (JS)
- 有条件地以角度显示链接.js
- JavaScript 函数不显示链接地址
- 显示链接的内容
- 在UI中显示链接函数angularJs的数据
- J汤html解析样式=“;显示:无;不要显示链接
- 将逻辑与幻灯片和隐藏/显示链接起来
- 可以在我的网站的另一个网站的地址栏中显示链接吗
- 如果低于特定的浏览器宽度,请不要显示链接
- 使用javascript在if条件内显示链接
- 如何在文本框中显示链接,并让按钮将其保存到数据库中
- 当用户单击“显示链接”时,显示密码,再次单击时将其隐藏