【问题标题】:AngularJS 1.2.0 ngBindHtml and trustAsHtml not working with ngModelAngularJS 1.2.0 ngBindHtml 和 trustAsHtml 不适用于 ngModel
【发布时间】:2013-11-06 16:44:03
【问题描述】:

我觉得这应该很容易,因为我使用 ngBindHtmlUnsafe 让它与 Angular 1.0.8 完美配合。我在 API 文档和 StackOverflow 上阅读了我现在需要使用 $sce.trustAsHtml() 和 ngBindHtml 但我似乎无法让它工作。

这基本上是我使用的格式:

var myApp = angular.module('myApp', []);

function myController($scope, $sce){
    $scope.myHtml = $sce.trustAsHtml($scope.sourceText);
}

html:

<html ng-app="myApp">

  <head>
    <script data-require="angular.js@1.2.0-rc3" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div ng-controller="myController">
      <textarea ng-model="sourceText"></textarea>

      <div ng-bind-html="myHtml"></div>
    </div>
  </body>

</html>

我认为它会这么简单,但我一定是错的并且遗漏了一些东西。

我把这个简单的例子丢给了 Plunker:http://plnkr.co/edit/ZX4dONBlzv1X8BcO1IBV?p=preview

【问题讨论】:

    标签: angularjs ng-bind-html


    【解决方案1】:

    这就是你要找的吗? http://plnkr.co/edit/IZkzsuKHvbYiyV07CGqp

    // would strongly suggest including sanitize in your scripts and injecting it
    // into your app here to prevent "unsafe as safe" errors
    var myApp = angular.module('myApp', ['ngSanitize']);
    
    myApp.controller('myController', ['$scope', '$sce', function myController($scope, $sce){
      $scope.myHtml = "initial";  //not needed, for testing
    
      $scope.changeText = function() {
        $scope.myHtml = $sce.trustAsHtml($scope.sourceText);
      }
    }]);
    

    HTML:

      <head>
        <script data-require="angular.js@1.2.0-rc3" data-semver="1.2.0-rc3-nonmin" src="http://code.angularjs.org/1.2.0-rc.3/angular.js"></script>
        <script src="http://code.angularjs.org/1.2.0-rc.3/angular-sanitize.min.js"></script>
        <link rel="stylesheet" href="style.css" />
        <script src="script.js"></script>
      </head>
    
      <body>
        <div ng-controller="myController">
          <textarea ng-model="sourceText" ng-change="changeText()"></textarea>
    
          <div ng-bind-html="myHtml"></div>
        </div>
      </body>
    
    </html>
    

    【讨论】:

    • 这正是我正在寻找的,但由于某种原因,当我在我的应用程序中执行相同操作(重新格式化控制器和添加新功能等)时,我的控制台现在给了我这个错误:@987654324 @ 这对我来说没有直接意义,因为 ngModel 和 ngClass 是核心的一部分......
    • 没问题。很高兴我能帮忙:)
    • @ryanlutgen 如何反转您的解决方案,例如:我已经有分配给 $scope 变量的 html 代码。在 ng-model 中使用。所以我想在 textarea 中显示它,而不是作为代码,而是作为文本。 (对于summernote 编辑器)
    猜你喜欢
    • 2013-11-03
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2018-05-26
    • 2018-12-14
    • 1970-01-01
    相关资源
    最近更新 更多