Search code examples
angularjsng-bind-htmlng-bind

how to convert string value to html element using angular?


I've tried bind a one page html to model window by angular HTTP call and ng-bind-html tag also included the ngSanitize js core. but It is working without HTML element.
My Code: 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>

Controller

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

Render 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>

You can refer below image it doesn't showing HTML elements enter image description here


Solution

  • From a quick look at the source for the $sanitize whitelist, it looks like input elements are not allowed by default.

    You could add them to the whitelist, but in this case the HTML is coming from your server and I would expect it to be trustworthy. So the simplest solution would be to use $sce.trustAsHtml to allow all elements in your HTML.

    To do that, you would change your Login function like so:

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