2015-01-02 34 views
5

基本上,我有这样的代码在我的模板:显示链接有条件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> 

正如你可以看到,我想显示一个可点击的URL时entry.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> 

但我会被重复重复几乎相同的比较,它看起来更糟。你们如何处理这个问题?

+1

这可能会帮助你:http://stackoverflow.com/questions/15810278/if-else-statement-in-angularjs-templates – Blauharley

+0

使用' '那么你可以简单地使用'true/false' – Satpal

回答

5

您可以试试。

<div ng-show="!link">hello</div> <div ng-show="!!link"><a href="{{link}}">hello</a></div>

但是,你正在使用应该罚款的ngSwitch

-1

我建议有一个纳克级=“{‘的className’:whenEntryURLisWhatever}”在TD,并使其改变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。

$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> 
+0

什么ng-click?我不知道你在说什么。你建议在CSS中隐藏未使用的元素吗?它现在比我现在做的更好吗? –

+0

没有,在你的CSS你可以有'.className span {text-decoration:underline;光标:指针; ''和其他你想要的链接样式。然后在你的范围内,有'ng-click =“yourFunction()”' –

+0

我已经编辑了答案,试着更好地解释这一点。 –

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

    } 
});