如何用AngularJS模型动态添加新输入使用JavaScript?

时间:2015-01-12 10:40:26

标签: javascript html angularjs

我有AngularJS控制器:

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

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

和HTML代码:

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

但在页面上,我看到Hello, {{name}}!,空输入和Ann名称。如何设置节目名称的输入和div?我在输入中更改名称并在div中更改了名称?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

ng-html compile不编译绑定,只解析静态html。如果您还希望在字符串中编译语法,则需要为此实现自定义指令:

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

然后你可以编译:

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