Insert HTML into view from AngularJS controller

前端 未结 18 1774
Happy的楠姐
Happy的楠姐 2020-11-21 06:00

Is it possible to create an HTML fragment in an AngularJS controller and have this HTML shown in the view?

This comes from a requirement to turn an

18条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 06:44

    For Angular 1.x, use ng-bind-html in the HTML:

    At this point you would get a attempting to use an unsafe value in a safe context error so you need to either use ngSanitize or $sce to resolve that.

    $sce

    Use $sce.trustAsHtml() in the controller to convert the html string.

     $scope.thisCanBeusedInsideNgBindHtml = $sce.trustAsHtml(someHtmlVar);
    

    ngSanitize

    There are 2 steps:

    1. include the angular-sanitize.min.js resource, i.e.:

    2. In a js file (controller or usually app.js), include ngSanitize, i.e.:
      angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize'])

提交回复
热议问题