2013-10-28 62 views
3

我覺得這應該是非常簡單的,因爲我已經使用ngBindHtmlUnsafe與Angular 1.0.8完美合作。我閱讀了API文檔和StackOverflow,現在需要使用$sce.trustAsHtml()ngBindHtml,但我似乎無法使其工作。AngularJS 1.2.0 ngBindHtml和trustAsHtml不適用於ngModel

這基本上是我使用給予我閱讀的格式:

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> 

我認爲這將是這個簡單,但我一定是錯的,失去了一些東西。

我放棄了這個簡單的例子,一個Plunker:http://plnkr.co/edit/ZX4dONBlzv1X8BcO1IBV?p=preview

回答

12

這是你在找什麼? 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> 
+0

這正是我期待的,但由於某種原因,當我做同樣的我的應用程序(重新格式化控制器和添加新的功能,等等)我的控制檯現在給我這個錯誤:'錯誤:[$ compile:ctreq]'ngClass'指令所需的控制器'ngModel',找不到!'這對ngModel和ngClass沒有直接意義是核心的一部分... – tehaaron

+0

沒有找到錯字;)謝謝! – tehaaron

+0

沒問題。很高興我可以幫助:) – ryanlutgen