混淆角表达式

Confuse about angular expressions

本文关键字:表达式      更新时间:2023-09-26

这就是我想要实现的:当用户输入一些文本时,我会找到字符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>');
            }
        });

但结果是,角转义<em>标记。例如,如果我输入apple,那么标签将显示<em>a</em>pple,而不是I want: a苹果。

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

要做到这一点,一个简单的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