有条件地以角度显示链接.js

Displaying link conditionally in Angular.js

本文关键字:显示 链接 js 有条件      更新时间:2023-09-26

基本上,我的模板中有以下代码:

<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>