AngularJS 1.2.0 ngBindHtml and trustAsHtml not working with ngModel
Asked Answered
M

1

3

I feel like this should be really easy since I had it working perfectly with Angular 1.0.8 using ngBindHtmlUnsafe. I read on the API docs and on StackOverflow that I need to use $sce.trustAsHtml() with ngBindHtml now but I cannot seem to get it to work.

This is basically the format I am using given what I read:

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

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

html:

<html ng-app="myApp">

  <head>
    <script data-require="[email protected]" 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>

I thought it would be this straightforward but I must be wrong and missing something.

I dropped this simple example to a Plunker: http://plnkr.co/edit/ZX4dONBlzv1X8BcO1IBV?p=preview

Mana answered 28/10, 2013 at 1:22 Comment(0)
F
12

Is this what you're looking for? 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="[email protected]" 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>
Freeforall answered 28/10, 2013 at 2:1 Comment(2)
This is exactly what I am looking for but for some reason when I do the same in my app (reformatting controller and adding the new function, etc) my console is now giving me this error: Error: [$compile:ctreq] Controller 'ngModel', required by directive 'ngClass', can't be found! which doesn't make immediate sense to me since ngModel and ngClass are part of core...Mana
@Freeforall How to do reverse of your solution, for example: i have html code already which is assigned to $scope variable. which is used in ng-model. so i want to display that in textarea not as code, but as text. (For summernote editor)Incumbency

© 2022 - 2024 — McMap. All rights reserved.