2

All:

I wonder how can I set a OR operator on a HTML string in Angualar Template, something like:

<div>{{value || <h6>No Header for now.</h6>}}</div>

The logic is if value is a string but not undefined, we show the value text, otherwise we show a error "No Header for Now" wrapped up by <h6>.

I do not know why this expression can not be correctly interpreted?

Thanks

Kuan
  • 11,149
  • 23
  • 93
  • 201
  • Hello! Please accept my answer if it solves your problem. :) [How does accepting an answer work?](http://meta.stackexchange.com/a/5235/170863) – GG. Apr 25 '16 at 20:23
  • @GG. Thanks, I gave the UPVOTE to the answer, cos it helps. – Kuan Apr 25 '16 at 20:42

2 Answers2

1

This can be solved with ng-if:

<div ng-if="value">value</div>
<div ng-if="!value"><h6>No Header for now.</h6></div>

You can add specific attributes (e.g. class) and/or directives (e.g. ng-click) on each <div>.

The problem with using a single element is that you have to repeat your condition several times:

<div ng-class="{ value: 'class1', !value: 'class2' }"
     ng-click="value ? action1() : action2()"
     ng-bind-html="value || html">
</div>
GG.
  • 21,083
  • 14
  • 84
  • 130
  • Thanks, this is also how I solve it right now, just currious how to do it in the way in my question – Kuan Apr 19 '16 at 21:18
  • Ok nice! I edited my answer to add the disadvantage in my opinion to hold a condition with a single element. Hope it could help you. :) – GG. Apr 19 '16 at 21:27
0

You have to put a string, not an expression: <h6>No Header for now.</h6> is an invalid js expression. '<h6>No Header for now.</h6>' is a string and can be displayed in the {{ }}.

<div>{{value || '<h6>No Header for now.</h6>' }}</div>

or

<div>{{value != null ? value : '<h6>No Header for now.</h6>' }}</div>

I'm convinced the 2nd works.

EDIT:

If you want to add html code in the {{ }}, it is another problem. See AngularJS : Insert HTML into view, the filter 'sanitize' in 2nd answer should help you ( call {{ '<h1>test</h1>' | sanitize }} and it should work.

EDIT 2:

In a js file:

angular.module('yourapp')
.filter("sanitize", ['$sce', function($sce) {
  return function(htmlCode){
    return $sce.trustAsHtml(htmlCode);
  }
}]);

In view:

<div>{{value || '<h6>No Header for now.</h6>' | sanitize }}</div>

In dont know if you need 'ngResource' to use $sce, if it doesn't work, you will have to install angular-resource :/

Community
  • 1
  • 1
  • Thanks, but I guess I must miss something, when I use yours, it just show the expression as plain text( but the h6 style works ) – Kuan Apr 19 '16 at 20:42
  • Thanks, could u show me what it looks like in my case? – Kuan Apr 19 '16 at 20:54