3

Is it possible to render html codes inside an angularjs expression? Something like this code:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    </head>
    <body ng-app="myApp">
        {{
            1+2 === 3 ? 
            '<span>Hello World!</span>' 
                : 
            "HI" 
        }}
    </body>
    <script>
    var app = angular.module('myApp', []); 
    </script>
</html>
2
  • Care to provide a code? Documentation seems to not answer clearly and precisely my question Commented Mar 10, 2016 at 8:29
  • Great, two answers suggest to use a different solution, and one comment by dirkk says it is easy and gives us a hint. In the end nobody gives the answer, which is what people come here for. Commented Apr 13, 2017 at 9:44

2 Answers 2

2

I think there's definitely a better solution to this using ng-if. Having these huge angular expressions with HTML inside defeats the purpose in my opinion. What I'd do is something like this:

<body ng-app="myApp">
    <span ng-if="1 + 2 === 3">Hello World!</span>
    <p ng-if="1 + 2 !== 3">HI</p>
</body>

This a lot more readable to me.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh ok seems like I really need to use that method I was hoping I can use something similar to Django's conditional template tags
You could also use ngBindHtml docs.angularjs.org/api/ng/directive/ngBindHtml , but this solution seems a lot nicer if you ask me.
1

Expression are used for something to be parsed but for your required condition you can simply use ng-if like:

<body ng-app="myApp">
        <span ng-if="1+2 === 3">Hello World!</span> 
        <span ng-if="1+2 !== 3">HI</span>  
</body>

1 Comment

Oh ok seems like I really need to use that method I was hoping I can use something similar to Django's conditional template tags

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.