使用 ng-bind-html 和 $sce.trustAsHtml 创建一个带有 ng-model 绑定的字符串
Using ng-bind-html and $sce.trustAsHtml create a string with ng-model binding
我想动态创建表单。在我的控制器中,我创建了一个字符串
var str = "<input type='text' value='" + $scope.selectedData.code + "' class='form-control' />";
$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);
也不行。谁能知道这是怎么回事?
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
});
}
}
});
我想动态创建表单。在我的控制器中,我创建了一个字符串
var str = "<input type='text' value='" + $scope.selectedData.code + "' class='form-control' />";
$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);
也不行。谁能知道这是怎么回事?
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
});
}
}
});