How to output html through AngularJS template?

后端 未结 5 2032
醉梦人生
醉梦人生 2020-12-15 16:27

{{ revision.title }}

The title outputs fine, but the content - does

相关标签:
5条回答
  • 2020-12-15 17:03

    I created an ng-html directive that does the same basic thing that ng-bind-html-unsafe used to do. However, I strongly suggest that you only use it with caution. It could easily open your site up to malicious attacks. So know what you're doing before you implement it:

    .directive('ngHtml', ['$compile', function($compile) {
        return function(scope, elem, attrs) {
            if(attrs.ngHtml){
                elem.html(scope.$eval(attrs.ngHtml));
                $compile(elem.contents())(scope);
            }
            scope.$watch(attrs.ngHtml, function(newValue, oldValue) {
                if (newValue && newValue !== oldValue) {
                    elem.html(newValue);
                    $compile(elem.contents())(scope);
                }
            });
        };
    }]);
    

    And then you would use it as:

    <div ng-html="revision.content"></div>
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-15 17:08

    So the fix is this:

    include angular-sanitize.min.js from http://code.angularjs.org/ and include it in your module:

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

    and then you're free to use ng-bind-html

    0 讨论(0)
  • 2020-12-15 17:18

    What version are you using? If you are using less than 1.2 you can try ngBindHtmlUnsafe

    0 讨论(0)
  • 2020-12-15 17:27

    I know it's an older question, but you can also trust the value using $sce in your controller:

    $scope.revision.content = $sce.trustAsHtml($scope.revision.content);
    

    After that, ng-bind-html will work.

    0 讨论(0)
  • 2020-12-15 17:28

    according to Official AngularJs Doc about ngBindHtml you must inject ngSanitize into your app dependencies

    Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default, the resulting HTML content will be sanitized using the $sanitize service. To utilize this functionality, ensure that $sanitize is available, for example, by including ngSanitize in your module's dependencies (not in core Angular). In order to use ngSanitize in your module's dependencies, you need to include "angular-sanitize.js" in your application.

    Then you can install ngSanitize module by there ways:

    1 - using bower

    bower install --save angular-sanitize
    

    2 - using npm

    npm install --save angular-sanitize
    

    3 - manually by download angular-sanitize.js file from code.angularjs.org path which include all angularJs files categories by version number like @Xeen answer

    See More about install ngSanitize module from Oficial angularJs github repository for install angular-sanitize

    0 讨论(0)
提交回复
热议问题