Angularjs 使用ng bind html和$sce.trustAsHtml创建具有ng模型绑定的字符串

Angularjs 使用ng bind html和$sce.trustAsHtml创建具有ng模型绑定的字符串,angularjs,ng-bind-html,Angularjs,Ng Bind Html,我想动态创建表单。在我的控制器中,我创建了一个字符串 var str = "<input type='text' value='" + $scope.selectedData.code + "' class='form-control' />"; $scope.htmlString = $sce.trustAsHtml(str); var-str=”“; $scope.htmlString=$sce.trustAsHtml(str); 在我的html页面中 <div ng-

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

var str = "<input type='text' value='" + $scope.selectedData.code + "' class='form-control' />";
$scope.htmlString = $sce.trustAsHtml(str);
var-str=”“;
$scope.htmlString=$sce.trustAsHtml(str);
在我的html页面中

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

我得到了值,但没有约束力。 我也试着用

var str = "<input type='text' ng-model='" + $scope.selectedData.code + "' class='form-control' />";
$scope.htmlString = $sce.trustAsHtml(str);
var-str=”“;
$scope.htmlString=$sce.trustAsHtml(str);
也不起作用。有人知道这是怎么回事吗?

HTML:

添加指令:
编译模板

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

JS:

angular.module('ngApp',['ngSanitize']))
.controller('controller1',['$scope','$sce',函数($scope,$sce){
var str=“”;
$scope.htmlString=$sce.trustAsHtml(str);
}])
.directive('compileTemplate',函数($compile,$parse){
返回{
链接:功能(范围、元素、属性){
var parsed=$parse(attr.ngBindHtml);
函数getStringValue(){
return(已解析(范围)| |“”).toString();
}
//如果模板更改,请重新编译
作用域.$watch(getStringValue,函数(){
$compile(element,null,-9999)(scope);//9999使其跳过指令,这样我们就不会重新编译自己
});
}
}
});
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
            });
        }
    }
});