混淆 angular 表达式

Confuse about angular expressions

这是我想要实现的:当用户输入一些文本时,我会找到字符 a 并使用 <em> 标记在另一个 <label> 中强调它,这是我的html 标记:

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

如上所示,我正在使用 demoController 中的方法 emphasize 来做强调工作:

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

但结果是,angular 转义了 <em> 标签。例如,如果我输入 apple,那么标签将显示 <em>a</em>pple,而不是我想要的:apple.

那么为什么会这样呢?有什么方法可以防止这种情况发生或有其他方法吗?

要做到这一点,一个简单的 ng-bind-hmtl 就可以了:

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

但这并不是很安全,因此最好将其添加到您的控制器上:

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);
            }
        });

向您的模块添加过滤器:

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

在您看来:

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