我想动态更改表单输入,并且我尝试使用 ng-bind-html 执行此操作,但仅显示标签,文本框不会出现在 DOM 上。这里必须在 ctrl.content 中写入的内容取决于来自服务器的值。
注意
type value will be coming from server , and it can be dynamic
HTML
<div ng-bind-html="ctrl.content">
Controller
function myCtrl(type) {
var ctrl = this;
switch (type) {
case 1:
ctrl.content = " <div> Input : <input type=\"text\" > </div> ";
break;
case 2:
ctrl.content = " <div> Input : <input type=\"textarea\" > </div> ";
break;
default:
}
Dom 元素:
<div class="padding ng-binding ng-scope" ng-bind-html="addMeassurments.content"> <div> Input : </div> </div>
最佳答案
首先,你的作业完全错误
ctrl.content = " <div> Input : <input type=\"text\" > </div> ";
您应该将标记分配给 $scope 属性。例如
$scope.content = " <div> Input : <input type=\"text\" > </div> ";
其次,您应该使用 $sce service清理 html。 Here's a plnkr此代码演示了预期行为
var app = angular.module('plunker', []);
app.controller('Ctrl', function($scope, $sce) {
$scope.name = 'World';
var ctrl = this;
$scope.click = function myCtrl(type) {
switch (type) {
case 1:
$scope.content = $sce.trustAsHtml("<div> Input : <input type=\"text\" > </div> ");
break;
case 2:
$scope.content = $sce.trustAsHtml(" <div> Input : <textarea></textarea> </div> ");
break;
default:
}
}
});
另请注意,我将您的标记从 input type="textarea" 更改为 textarea 元素。
关于javascript - 如何在 Angular JS 中动态添加输入表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43936008/