An elegant way to show href based on a condition

I need to show the tag <a>. But depending on whether the value exists or not, I need to set href.

This is what I have:

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

If source.elementequal to 0, then nothing should happen when you click on the value source.element( href="")

Else, the page should be redirected according to href.

Is there a better way to do this since this duplicate code?

Thanks..

+4
source share
5 answers

create a method in the field

$scope.getUrl = function(source){
  return source.element==0 ? '#' :  '#/resource/'+source.a+'/'+source.b+'/val';
}

then call from view

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

For angular markup it is better to use . ngHref

, href angular, .

+4

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

Use ng-switchto reduce hours and code duplication:

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

In your controller:

$scope.source.url = $scope.source.element === 0 ? '' :  '#/resource/' + $scope.source.a + '/' + $,scope.source.b + '/val';

And in your markup

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

Create a directive with two type attributes conditionand url:

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

0
source

Source: https://habr.com/ru/post/1623874/


All Articles