使用ng-bind-html和$ sce.trustAsHtml创建具有ng-model绑定的字符串 [英] Using ng-bind-html and $sce.trustAsHtml create a string with ng-model binding

查看:93
本文介绍了使用ng-bind-html和$ sce.trustAsHtml创建具有ng-model绑定的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建动态表格.在控制器内部,我创建了一个字符串

I want to create dynamically forms. Inside my controller i create a string

var str = "<input type='text' value='" + $scope.selectedData.code + "' class='form-control' />";
$scope.htmlString = $sce.trustAsHtml(str);

以及在我的html页面

and in my html page

<div ng-bind-html="htmlString"></div>

我得到值,但没有约束力. 我也尝试

i get the value but is not binding. I try also with

var str = "<input type='text' ng-model='" + $scope.selectedData.code + "' class='form-control' />";
$scope.htmlString = $sce.trustAsHtml(str);

也不起作用.谁能知道这是怎么工作的?

also doesn't work. Can anyone know how can this work?

推荐答案

HTML:

添加指令:compile-template

<div ng-bind-html="htmlString" compile-template></div>

JS:

angular.module('ngApp', ['ngSanitize'])
.controller('controller1', ['$scope','$sce', function($scope, $sce) {
    var str = "<input type='text' ng-model='" + $scope.selectedData.code + "' class='form-control' />";
    $scope.htmlString = $sce.trustAsHtml(str);
}])
.directive('compileTemplate', function($compile, $parse){
    return {
        link: function(scope, element, attr){
            var parsed = $parse(attr.ngBindHtml);
            function getStringValue() {
                return (parsed(scope) || '').toString();
            }

            // Recompile if the template changes
            scope.$watch(getStringValue, function() {
                $compile(element, null, -9999)(scope);  // The -9999 makes it skip directives so that we do not recompile ourselves
            });
        }
    }
});

这篇关于使用ng-bind-html和$ sce.trustAsHtml创建具有ng-model绑定的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆