【问题标题】:how to convert string value to html element using angular?如何使用角度将字符串值转换为html元素?
【发布时间】:2015-09-20 16:37:31
【问题描述】:

我尝试通过角度 HTTP 调用将一页 html 绑定到模型窗口,并且 ng-bind-html 标记还包括 ngSanitize js 核心。但它在没有 HTML 元素的情况下工作。
我的代码:HTML

<div class="myModels" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" data-backdrop="true" ng-show="showModel">
    <div class="modal-dialog" role="document" ng-bind-html = "ModelContent"></div>
</div>

控制器

$scope.Login = function(path){
    $http.post('http:'+path).success(function(result){$scope.ModelContent = result;})
}

渲染 HTML:

<div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close" ng-model="">
                <span aria-hidden="true">&times;</span>
                <span class="sr-only">Close</span>
            </button>
            <h4 class="modal-title" id="myModalLabel">Login</h4>
        </div>
        <div class="modal-body">
            <div class="row">
                <div class="col-md-10">
                    <label>User Name</label>
                    <input type="text" name="username" maxlength="10" class="form-control" ng-model=""> 
                </div>
            </div>
            <div class="row">
                <div class="col-md-10">
                    <label>Password</label>
                    <input type="password" name="password" maxlength="15" class="form-control" ng-model=""> 
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button name="SignIn" class="btn btn-success pull-right">Log in</button>
        </div>
    </div>

您可以参考下图它不显示 HTML 元素

【问题讨论】:

  • 你能把代码贴出来吗?

标签: angularjs ng-bind-html ng-bind


【解决方案1】:

快速查看the $sanitize whitelist 的来源,似乎默认情况下不允许使用input 元素。

您可以将它们添加到白名单中,但在这种情况下,HTML 来自您的服务器,我希望它是值得信赖的。因此,最简单的解决方案是 use $sce.trustAsHtml 允许 HTML 中的所有元素。

为此,您可以像这样更改 Login 函数:

// Note that you'll need to inject $sce into your controller
$scope.Login = function(path){
    $http.post('http:'+path)
    .success(function(result) {
        $scope.ModelContent = $sce.trustAsHtml(result);
    });
}

【讨论】:

    【解决方案2】:

    将此代码放入您的控制器中 控制器.js

    $rootScope.errorMessage = 'Account activated successfully, please <a href="/">Login</a> and other <em>stuff</em> with your username and password';
    

    在您的 html 页面中也使用此代码

    <h5 ng-bind-html="errorMessage"></h5>
    

    【讨论】:

    猜你喜欢
    • 2014-08-30
    • 2021-04-27
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 2018-04-29
    相关资源
    最近更新 更多