How to surround text with tag conditionally in AngularJS? for example:
function Controller($scope){
$scope.showLink = true or false, retrieved from server;
$scope.text = "hello";
$scope.link = "..."
}
if {{showLink}} is false
<div>hello</div>
else
<div><a href="{{link}}">hello</a></div>
ngSwitch
is suitable for that:
<div ng-switch="!!link">
<a ng-href="{{link}}" ng-switch-when="true">linked</a>
<span ng-switch-when="false">notlinked</span>
</div>
As far as I can tell there's no out-of-the-box feature to do this. I wasn't really satisfied with the other answers because they still require you to repeat the inner contents in your view.
Well, you can fix this with your own directive.
app.directive('myWrapIf', [
function()
{
return {
restrict: 'A',
transclude: false,
compile:
{
pre: function(scope, el, attrs)
{
if (!attrs.wrapIf())
{
el.replaceWith(el.html());
}
}
}
}
}
]);
Usage:
<a href="/" data-my-wrap-if="list.indexOf(currentItem) %2 === 0">Some text</a>
"Some text" will be a link only if the condition is met.
Try
<div ng-show="!link">hello</div>
<div ng-show="!!link"><a href="{{link}}">hello</a></div>
You can use the ng-switch
directive.
<div ng-switch on="showLink">
<div ng-switch when="true">
<a ng-href="link">hello</a>
</div>
<div ng-switch when="false">
Hello
</div>
</div>
Modified version of Casey's answer to support AngularJS expressions:
app.directive('removeTagIf', ['$interpolate', function($interpolate) {
return {
restrict: 'A',
link: function(scope, el, attrs) {
if (scope.$eval(attrs.removeTagIf))
el.replaceWith($interpolate(el.html())(scope));
}
};
}]);
Usage:
<a href="/" remove-tag-if="$last">{{user}}'s articles</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With