根据条件显示href的优雅方式

4

我需要展示一个 <a> 标签。但是根据某个值是否存在,我需要设置 href

这是我目前的代码:

<a ng-show="source.element!=0" "href="#/resource/{{source.a}}/{{source.b}}/val">
     {{source.element}})
</a>
<a ng-show="source.element==0" "href="">{{source.element}}</a>

如果 source.element 的值为0,则单击 source.element 的值 (href = "") 不会发生任何事情。
否则,页面必须根据 href 重定向。
是否有更好的方法来避免代码重复?
谢谢。

在<a>标签外使用ng-show来隐藏和显示整个标签。否则,如果您想更改“href”,则使用函数获取源URL。 - Thangadurai
@user3141852 提醒一下,使用 ng-showng-hide 的性能比使用 ng-if 差,因为元素及其任何被监视的表达式都会留在 DOM 中。 - GregL
5个回答

5
在作用域中创建一个方法。
$scope.getUrl = function(source){
  return source.element==0 ? '#' :  '#/resource/'+source.a+'/'+source.b+'/val';
}

然后从视图中调用

<a ng-href="{{getUrl(source)}}">
     {{source.element}})
</a>

对于Angular标记,最好使用ngHref,因为如果用户在Angular加载之前单击href,它会跳转到错误的地址。

1
使用ngHref可能会稍微好一些,但除此之外,都是一样的。 - GregL
谢谢你的回答。有一个小问题。当它返回 # 时,URL 从 localhost:8001/#/something 变为 localhost:8001/#。它的行为与使用 href="" 不同。 - Thiyagu
@GregL 谢谢提到 ngHref。我已经更新了我的回答。 - Anik Islam Abhi
@GregL 我没有写来隐藏的意思。 - Anik Islam Abhi
@AnikIslamAbhi 但它的行为不像 href=""。当我使用 href="" 时,单击时什么也不会发生。但是如果我按照您的指示操作,页面将重定向到 localhost:8001 - Thiyagu
显示剩余2条评论

0

你可以使用 ng-if

<div ng-if="source.element!=0"><a ng-href="your-url">{{sourceElement}</a></div>
<div ng-if="source.element==0"><a ng-href="">{{sourceElement}}</a></div> 

ngif 文档


0
使用ng-switch来减少监视器数量和代码重复:
<span ng-switch="source.element">
    <a ng-switch-when="0">
        {{source.element}}
    </a>
    <a ng-switch-default ng-href="#/resource/{{source.a}}/{{source.b}}/val">
        {{source.element}}
    </a>
</span>

0
在你的控制器中:
$scope.source.url = $scope.source.element === 0 ? '' :  '#/resource/' + $scope.source.a + '/' + $,scope.source.b + '/val';

而在你的标记中

<a "ng-Href={{source.url}}>{{source.element}}</a>

0
创建一个带有两个属性的指令,如conditionurl:
app.directive('anchor', function() {
    return {
        scope: {
            condition: '=expr',
            url: '@',
            prompt: '@'
        },
        restrict: 'AE',
        replace: 'true',
        template: '<div>' +
                      '<div ng-if="condition">' + 
                          '<a ng-href="{{url}}">{{prompt}}</a>' + 
                      '</div>' +
                      '<div ng-if="!condition">{{prompt}}</div>' +
                  '</div>'
    };
});

<anchor expr="1 === 1" url="#/test" prompt="test" />

jsfiddle链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接