hh54188
hh54188

Reputation: 15626

Confuse about angular expressions

Here is what I want achieve: when user input some text, I will find the character a and using <em> tag to emphasize it in another <label>, here is my html markup:

    <div ng-controller="demoController">
        <input type="text" ng-model="input" />
        <label>{{emphasize()}}</label>  
    </div>

As showing above, I'm using method emphasize in demoController to do emphasize job:

        myapp.controller('demoController', function ($scope) {
            $scope.input = 'Hello';
            $scope.emphasize = function () {
                return $scope.input.replace(/a/g, '<em>a</em>');
            }
        });

But the result is, the angular escape the <em> tag. For instance , if I input apple, then the label would show <em>a</em>pple, not I want: apple.

So why does this happened? Is there a way I can prevent this happen or another way to do it?

Upvotes: 0

Views: 68

Answers (2)

MoLow
MoLow

Reputation: 3084

add a filter to your module:

myapp.filter('unsafe', ['$sce', function ($sce) {
    return function (a) { return $sce.trustAsHtml(a) };
}]);

and in your view:

<span ng-bind-html="emphasize() | unsafe"></span

Upvotes: 0

Pierre-Alexandre Moller
Pierre-Alexandre Moller

Reputation: 2354

To do so a simple ng-bind-hmtl will do the trick :

<span ng-bind-html="emphasize()"></span> 

But this is not really safe so it's always better to add this on your controller :

myapp.controller('demoController', function ($scope, $sce) {
            $scope.input = 'angularJS';
            $scope.emphasize = function () {
                var res = $scope.input.replace(/a/g, '<em>a</em>');
                return $sce.trustAsHtml(res);
            }
        });

Upvotes: 1

Related Questions