Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

angularjs - Using ng-bind-html and $sce.trustAsHtml create a string with ng-model binding

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...