0

I have AngularJS controller:

$scope.name = "Ann";
$scope.test = "Hello, {{name}}!";

var element = document.createElement("input");
element.setAttribute('ng-model', "name");
document.getElementById("preview").appendChild(element);

And HTML-code:

<div id="preview">
    <p ng-bind-html="test"></p>
</div>
{{name}}

But at page I see Hello, {{name}}!, empty input and Ann name. How to setting input and div for show name? That I change name in input and name changed in div?

2 Answers 2

1

Checkout this plnkr

 $scope.name = "Ann";
$scope.test = "Hello, {{name}}!";

var element = document.createElement("input");
element.setAttribute('ng-model', "name");
document.getElementById("preview").appendChild(element);

$compile(document.getElementById("preview"))($scope);
Sign up to request clarification or add additional context in comments.

2 Comments

It isn't a true solution for me, because the $scope.test is dynamic string. And I don't know, how many {{name}} I have
It will be updated when your $scope.name will update. Your Hello 'name' is sync to your input box. So whatever there in $scope.name will be shown. :)
1

ng-html compile does not compile bindings but only parses the static html. If you want to also have your syntax compiled in strings you need to implement custom directive for that:

app.directive('ngHtmlCompile', ["$compile", function ($compile) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngHtmlCompile, function (newValue, oldValue) {
                element.html(newValue);
                $compile(element.contents())(scope);
            });
        }
    }
}]);

and then you can compile:

<div ng-html-compile="Hello, {{name}}!"></div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.