2

I am using AngularJS v1.2.1.

The improved ng-bind-html directive allows me to trust unsafe Html into my view.

Example

HTML:

<div ng-repeat="example in examples" ng-bind-html="example.content()"></div>

JS:

function controller($scope, $sce)
{

    function ex()
    {
        this.click = function ()
        {
            alert("clicked");
        }

        this.content() = function ()
        {
            //if
            return $sce.trustAsHtml('<button ng-click="click()">some text</button>'); 
            // no problem, but click is not called

            //when
            return $sce.parseAsHtml('<button ng-click="click()">some text</button>'); 
            //throw an error
        }
    }

    $scope.examples = [new ex(), new ex()];

}

My question is, how to bind HTML content that may contain Angular expressions or directives ??

1 Answer 1

5

If you need dynamic templates per element, as your question suggests, one solution would be to use $compile within a directive to parse the HTML within the context of the local scope. A simple version of this is shown in this Plunk.

An example directive:

app.directive('customContent', function($compile) {
  return function(scope, el, attrs) {
    el.replaceWith($compile(scope.example.content)(scope));
  }
});

The corresponding HTML:

<div ng-repeat="example in examples">
  <div custom-content></div>
</div>

Notice that, in the Plunk controller, I've pulled out the click function into the scope for simplicity, since in the template HTML you are calling click() in the context of the scope, not on the example object. There are a couple ways you could use a different click function for each example, if that's what you'd like to do. This egghead.io screencast has a good example of passing an expression into a directive explicitly; in your case, it could be a click function or the whole example object, depending on what you need.

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

2 Comments

well thanks for your answer, I know that answer from another question, I thought they integrated this solution with the 'parseAsHtml' function. if you could answer one more question, what does 'parseAsHtml' do ??
$sce.parseAsHtml (a convenience method for $sce.parseAs) calls $parse behind the scenes, which means it's looking for an Angular expression instead of an HTML string-- this may be why it's throwing an error for you.

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.