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

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

问题描述

我想动态创建表单.在我的控制器中,我创建了一个字符串

var str = "";$scope.htmlString = $sce.trustAsHtml(str);

并在我的 html 页面中

我得到了值但没有约束力.我也尝试使用

var str = "";$scope.htmlString = $sce.trustAsHtml(str);

也不起作用.任何人都可以知道这是如何工作的吗?

解决方案

HTML :

添加指令:compile-template

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){返回 {链接:功能(范围,元素,属性){var parsed = $parse(attr.ngBindHtml);函数 getStringValue() {return (parsed(scope) || '').toString();}//如果模板改变了重新编译scope.$watch(getStringValue, function() {$compile(element, null, -9999)(scope);//-9999 使它跳过指令,这样我们就不会重新编译自己});}}});

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

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 :

Add a directive: 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天全站免登陆