Reputation: 17880
I have to show an <a>
tag. But depending on whether a 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.element
is 0 , then nothing should happen on clicking on the value of source.element
(href=""
)
Else, the page must be redirected according to the href.
Is there a better way to do this since this duplicates code?
Thanks..
Upvotes: 4
Views: 8296
Reputation: 2973
Create a directive with two attributes like condition
and 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" />
The jsfiddle link.
Upvotes: 0
Reputation: 25352
create a method in scope
$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's better to use ngHref
.
Becuse if user click on href before angular load it'll go the wrong address.
Upvotes: 5
Reputation: 23768
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>
Upvotes: 0
Reputation: 38103
Use ng-switch
to reduce the number of watches 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>
Upvotes: 0
Reputation: 242
You can use 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>
Upvotes: 0