AngularJS-动态创建<text区域>使用ngSanitize不会't显示(其他元素显示)

AngularJS - Dynamically created <textarea> using ngSanitize doesn't show (other elements do)

本文关键字:显示 其他 元素 不会 使用 lt 创建 动态 text 区域 AngularJS-      更新时间:2023-09-26

我是AngularJS新手,尝试在单击button时动态创建textarea。我使用的是ngSanitize插件,代码有效,我可以插入带有一些文本的普通div,但当创建textarea时,它就不起作用了。元素甚至没有显示。

HTML:

<button class="btn bg-info" ng-click="insertReplyBox()">Reply</button>
<br>
<div class="row">
  <div class="col-lg-2" id="replyBox">
    <div ng-bind-html="replyBoxHTML"></div>
    <div ng-bind-html="replyBoxHTML1"></div>
  </div>
</div>

JS(角度控制器)

app.controller('messagesReadController', function($scope) {
  $scope.insertReplyBox = function() {
    console.log("reply clicked");
    $scope.replyBoxHTML = '<div>This works!!</div>';
    $scope.replyBoxHTML1 = '<textarea col="4" row="20" placeholder="placeholder"></textarea>'; //this doesn't work
  }
});

(我已经在另一个文件中添加了ngSanitize依赖项,所以这里不显示。)

使用不安全的

var app = angular.module('myApp', []);
app.controller('messagesReadController', function($scope) {
  $scope.insertReplyBox = function() {
    console.log("reply clicked");
    $scope.replyBoxHTML = '<div>This works!!</div>';
    $scope.replyBoxHTML1 = '<textarea col="4" row="20" placeholder="placeholder"></textarea>'; //this doesn't work
  }
});
 app.filter('unsafe', function ($sce) {
    return function (val) {
       return $sce.trustAsHtml(val);
    };
 });
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="messagesReadController">
<button class="btn bg-info" ng-click="insertReplyBox()">Reply</button>
<br>
<div class="row">
  <div class="col-lg-2" id="replyBox">
    <div ng-bind-html="replyBoxHTML"></div>
    <div ng-bind-html="replyBoxHTML1| unsafe"   ></div>
  </div>
</div>
 
</body>
</html>

我认为你做这件事的方式不对,使用angularJS,你应该避免最大限度地使用DOM(指令除外)

这个怎么样?

<button class="btn bg-info" ng-click="textareashow = !textareashow">Reply</button>
 <br>
 <div class="row" ng-show="textareashow">
   <div class="col-lg-2" id="replyBox">
     <textarea col="4" row="20" placeholder="placeholder"></textarea>
   </div>
 </div>