4

I got stuck with these problem and hope you can point me in the right direction.

Here is the fiddle.

Explainer

1) I receive some template html via ajax request, everything works fine this is what it looks:

        <div>
            <h2 class="splash" ng-bind="view.headline || 'That&#039;s cool'"></h2>
        </div>

As you already know if the view.headline this will output That's cool

2) Adding the template to the dom (just pseudo code)

<div id="thisIsMyTemplatePlaceholder"></div>
<script>
var templateFromAjax="<h2 ng-bind=\"view.headline||'That&#039;s cool'\"></h2>";
$("#thisIsMyTemplatePlaceholder").html(templateFromAjax);
</script>

3) Inspect the added HTML you see three '(apostrophe) on the ng-bind attribute and this causes the my error

<div id="thisIsMyTemplatePlaceholder">
<h2 ng-bind="view.headline||'That's cool'"></h2>
</div>

4) The Problem seems to be the jQuery.html() function because it decodes the specialcharacters.

jquery is transforming this: 'That&#039;s cool' into 'That's'
2
  • 1
    You should not be mixing jQuery in with Angular, if you have a template you want to paste into a page, you should use a directive. So to solve your problem, use ng-include to paste your template. Commented Dec 21, 2015 at 15:15
  • Can you elaborate on how your call for the template looks like? What is the URL structure? Commented Dec 21, 2015 at 15:31

3 Answers 3

1

Try escaping twice. One escape will be removed as html() unescapes your String, see here for reference.

'That\\'s cool'\">That's cool</h2>";

Now when you use .attr("ng-bind") the following will be the result

view.headline || 'That\'s cool

Is this your desired effect, or will only That&#039;s cool work?

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

Comments

1

Another way:

First, separate the template to another file, just easier that way:

myTemplate.html

<h2 ng-bind="view.headline || 'That\'s cool'"></h2> 
<!-- you can just escape the one apostraphe, but really, 
this logic doesn't belong in the html, but rather the 
controller or service which assigns a value to view.headline -->

Then you can include your template:

<div id="thisIsMyTemplatePlaceholder" ng-include="'myTemplate.html'"> </div>

A Plunker showing this working:

http://plnkr.co/edit/NlzTmlNMQCqHwqVxgCpQ?p=preview

1 Comment

That's working, but I'm still looking for a way to do this with jquery. Thanks for the plankr!
0

Have you tried:

<!-- you can just escape the one apostrophe -->
<h2 ng-bind="view.headline || 'That\'s cool'"></h2> 

Comments

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.