Insert HTML into view from AngularJS controller

前端 未结 18 1825
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:43

    Another solution, very similar to blrbr's except using a scoped attribute is:

    angular.module('app')
    .directive('renderHtml', ['$compile', function ($compile) {
        return {
          restrict: 'E',
          scope: {
            html: '='
          },
          link: function postLink(scope, element, attrs) {
    
              function appendHtml() {
                  if(scope.html) {
                      var newElement = angular.element(scope.html);
                      $compile(newElement)(scope);
                      element.append(newElement);
                  }
              }
    
              scope.$watch(function() { return scope.html }, appendHtml);
          }
        };
      }]);
    

    And then

    <render-html html="htmlAsString"></render-html>
    

    Note you may replace element.append() with element.replaceWith()

    0 讨论(0)
  • 2020-11-21 06:44

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

    <div ng-bind-html="thisCanBeusedInsideNgBindHtml"></div>
    

    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.:
      <script src="lib/angular/angular-sanitize.min.js"></script>

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

    0 讨论(0)
  • 2020-11-21 06:46

    Fortunately, you don't need any fancy filters or unsafe methods to avoid that error message. This is the complete implementation to properly output HTML markup in a view in the intended and safe way.

    The sanitize module must be included after Angular:

    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.js"></script>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular-sanitize.js"></script>
    

    Then, the module must be loaded:

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

    This will allow you to include markup in a string from a controller, directive, etc:

    scope.message = "<strong>42</strong> is the <em>answer</em>.";
    

    Finally, in a template, it must be output like so:

    <p ng-bind-html="message"></p>
    

    Which will produce the expected output: 42 is the answer.

    0 讨论(0)
  • 2020-11-21 06:47

    Here's a simple (and unsafe) bind-as-html directive, without the need for ngSanitize:

    myModule.directive('bindAsHtml', function () {
        return {
            link: function (scope, element, attributes) {
                element.html(scope.$eval(attributes.bindAsHtml));
            }
        };
    });
    

    Note that this will open up for security issues, if binding untrusted content.

    Use like so:

    <div bind-as-html="someHtmlInScope"></div>
    
    0 讨论(0)
  • 2020-11-21 06:50

    there is one more solution for this problem using creating new attribute or directives in angular.

    product-specs.html

     <h4>Specs</h4>
            <ul class="list-unstyled">
              <li>
                <strong>Shine</strong>
                : {{product.shine}}</li>
              <li>
                <strong>Faces</strong>
                : {{product.faces}}</li>
              <li>
                <strong>Rarity</strong>
                : {{product.rarity}}</li>
              <li>
                <strong>Color</strong>
                : {{product.color}}</li>
            </ul>
    

    app.js

     (function() {
    var app = angular.module('gemStore', []);    
    app.directive("     <div ng-show="tab.isSet(2)" product-specs>", function() {
    return {
      restrict: 'E',
      templateUrl: "product-specs.html"
    };
    });
    

    index.html

     <div>
     <product-specs>  </product-specs>//it will load product-specs.html file here.
     </div>
    

    or

    <div  product-specs>//it will add product-specs.html file 
    

    or

    <div ng-include="product-description.html"></div>
    

    https://docs.angularjs.org/guide/directive

    0 讨论(0)
  • 2020-11-21 06:51

    on html

    <div ng-controller="myAppController as myCtrl">
    
    <div ng-bind-html-unsafe="myCtrl.comment.msg"></div>
    

    OR

    <div ng-bind-html="myCtrl.comment.msg"></div
    

    on controller

    mySceApp.controller("myAppController", function myAppController( $sce) {
    
    this.myCtrl.comment.msg = $sce.trustAsHtml(html);
    

    works also with $scope.comment.msg = $sce.trustAsHtml(html);

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