somebody
somebody

Reputation: 1107

How to dynamic add new input with AngularJS model use JavaScript?

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?

Upvotes: 0

Views: 948

Answers (2)

Ali Habibzadeh
Ali Habibzadeh

Reputation: 11558

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>

Upvotes: 1

dhavalcengg
dhavalcengg

Reputation: 4713

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

Upvotes: 1

Related Questions