从 AngularJS 控制器将 HTML 插入视图

发布于 2025-01-07 12:56:43 字数 689 浏览 0 评论 0原文

是否可以在 AngularJS 控制器中创建 HTML 片段并将此 HTML 显示在视图中?

这是因为需要将不一致的 JSON blob 转换为 id: value 对的嵌套列表。因此,HTML 在控制器中创建,我现在希望显示它。

我已经创建了一个模型属性,但如果不打印 HTML,就无法在视图中呈现它。


更新

看来问题是由于将创建的 HTML 角度渲染为引号内的字符串而引起的。将尝试找到解决此问题的方法。

控制器示例:

var SomeController = function () {

    this.customHtml = '<ul><li>render me please</li></ul>';
}

视图示例:

<div ng:bind="customHtml"></div>

给出:

<div>
    "<ul><li>render me please</li></ul>"
</div>

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 inconsistent JSON blob into a nested list of id: value pairs. Therefore the HTML is created in the controller and I am now looking to display it.

I have created a model property, but cannot render this in the view without it just printing the HTML.


Update

It appears that the problem arises from angular rendering the created HTML as a string within quotes. Will attempt to find a way around this.

Example controller :

var SomeController = function () {

    this.customHtml = '<ul><li>render me please</li></ul>';
}

Example view :

<div ng:bind="customHtml"></div>

Gives :

<div>
    "<ul><li>render me please</li></ul>"
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

北城挽邺 2025-01-14 12:56:43

对于 Angular 1.x,在 HTML 中使用 ng-bind-html

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

此时您将收到 attempting to use an unsafe value in a safe context 错误,因此您需要使用 ngSanitize$sce 来解决这个问题。

$sce

在控制器中使用$sce.trustAsHtml()来转换html字符串。

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

ngSanitize

有 2 个步骤:

  1. 包含 angular-sanitize.min.js 资源,即:

    ;
    
  2. 在 js 文件(控制器或通常是 app.js)中,包含 ngSanitize,即:

    angular.module('myApp', ['myApp.filters', 'myApp.services', 
        'myApp.directives', 'ngSanitize'])
    

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'])
    
花想c 2025-01-14 12:56:43

您还可以像这样创建一个过滤器:

var app = angular.module("demoApp", ['ngResource']);

app.filter("trust", ['$sce', function($sce) {
  return function(htmlCode){
    return $sce.trustAsHtml(htmlCode);
  }
}]);

然后在视图中

<div ng-bind-html="trusted_html_variable | trust"></div>

注意:此过滤器信任传递给它的所有 html,并且如果将带有用户输入的变量传递给它,则可能会出现 XSS 漏洞。

You can also create a filter like so:

var app = angular.module("demoApp", ['ngResource']);

app.filter("trust", ['$sce', function($sce) {
  return function(htmlCode){
    return $sce.trustAsHtml(htmlCode);
  }
}]);

Then in the view

<div ng-bind-html="trusted_html_variable | trust"></div>

Note: This filter trusts any and all html passed to it, and could present an XSS vulnerability if variables with user input are passed to it.

卖梦商人 2025-01-14 12:56:43

Angular JS 在标签内显示 HTML

上面链接中提供的解决方案对我有用,该线程上的任何选项都不起作用。对于任何在 AngularJS 版本 1.2.9 中寻找相同内容的人,

这里有一份副本:

好的,我找到了解决方案:

JS:

$scope.renderHtml = 函数(html_code)
{
    返回 $sce.trustAsHtml(html_code);
};

HTML:

编辑:

这是设置:

JS 文件:

angular.module('MyModule').controller('MyController', ['$scope', '$http', '$sce',
    function ($scope, $http, $sce) {
        $scope.renderHtml = function (htmlCode) {
            return $sce.trustAsHtml(htmlCode);
        };

        $scope.body = '<div style="width:200px; height:200px; border:1px solid blue;"></div>'; 

    }]);

HTML 文件:

<div ng-controller="MyController">
    <div ng-bind-html="renderHtml(body)"></div>
</div>

Angular JS shows HTML within the tag

The solution provided in the above link worked for me, none of the options on this thread did. For anyone looking for the same thing with AngularJS version 1.2.9

Here's a copy:

Ok I found solution for this:

JS:

$scope.renderHtml = function(html_code)
{
    return $sce.trustAsHtml(html_code);
};

HTML:

<p ng-bind-html="renderHtml(value.button)"></p>

EDIT:

Here's the set up:

JS file:

angular.module('MyModule').controller('MyController', ['$scope', '$http', '$sce',
    function ($scope, $http, $sce) {
        $scope.renderHtml = function (htmlCode) {
            return $sce.trustAsHtml(htmlCode);
        };

        $scope.body = '<div style="width:200px; height:200px; border:1px solid blue;"></div>'; 

    }]);

HTML file:

<div ng-controller="MyController">
    <div ng-bind-html="renderHtml(body)"></div>
</div>
假装爱人 2025-01-14 12:56:43

幸运的是,您不需要任何花哨的过滤器或不安全的方法来避免该错误消息。这是以预期且安全的方式在视图中正确输出 HTML 标记的完整实现。

清理模块必须包含在 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>

然后,必须加载该模块:

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

这将允许您在来自控制器、指令等的字符串中包含标记:

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

,在模板中,必须像这样输出:

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

最后 产生预期的输出:42答案

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.

挽你眉间 2025-01-14 12:56:43

我今天尝试过,我发现的唯一方法是这个

I have tried today, the only way I found was this

<div ng-bind-html-unsafe="expression"></div>

|煩躁 2025-01-14 12:56:43

ng-bind-html-unsafe 不再有效。

这是最短的方法:

创建过滤器:

myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

在您看来:

<div ng-bind-html="customHtml | unsafe"></div>

PS 此方法不需要您包含 ngSanitize 模块。

ng-bind-html-unsafe no longer works.

This is the shortest way:

Create a filter:

myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });

And in your view:

<div ng-bind-html="customHtml | unsafe"></div>

P.S. This method doesn't require you to include the ngSanitize module.

月寒剑心 2025-01-14 12:56:43

在 html 上

<div ng-controller="myAppController as myCtrl">

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

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

在控制器上

mySceApp.controller("myAppController", function myAppController( $sce) {

this.myCtrl.comment.msg = $sce.trustAsHtml(html);

也适用于 $scope.comment.msg = $sce.trustAsHtml(html);

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);

记忆之渊 2025-01-14 12:56:43

我发现使用 ng-sanitize 不允许我在 html 中添加 ng-click 。

为了解决这个问题,我添加了一个指令。就像这样:

app.directive('htmldiv', function($compile, $parse) {
return {
  restrict: 'E',
  link: function(scope, element, attr) {
    scope.$watch(attr.content, function() {
      element.html($parse(attr.content)(scope));
      $compile(element.contents())(scope);
    }, true);
  }
}
});

这是 HTML:

<htmldiv content="theContent"></htmldiv>

祝你好运。

I found that using ng-sanitize did not allow me to add ng-click in the html.

To solve this I added a directive. Like this:

app.directive('htmldiv', function($compile, $parse) {
return {
  restrict: 'E',
  link: function(scope, element, attr) {
    scope.$watch(attr.content, function() {
      element.html($parse(attr.content)(scope));
      $compile(element.contents())(scope);
    }, true);
  }
}
});

And this is the HTML:

<htmldiv content="theContent"></htmldiv>

Good luck.

妖妓 2025-01-14 12:56:43

只需按照 Angular(v1.4) docs 使用 ngBindHtml 执行此操作,

<div ng-bind-html="expression"></div> 
and expression can be "<ul><li>render me please</li></ul>"

请确保将 ngSanitize 包含在模块的依赖关系。
那么它应该可以正常工作。

Just did this using ngBindHtml by following angular(v1.4) docs,

<div ng-bind-html="expression"></div> 
and expression can be "<ul><li>render me please</li></ul>"

Make sure you include ngSanitize in the module's dependencies.
Then it should work fine.

套路撩心 2025-01-14 12:56:43

另一个解决方案,与 blrbr 非常相似,除了使用作用域属性之外是:

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);
      }
    };
  }]);

然后

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

注意,您可以将 element.append() 替换为 element.replaceWith()

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()

度的依靠╰つ 2025-01-14 12:56:43

对于这个问题还有一个解决方案,即在 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< /strong>

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

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

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

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

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

百变从容 2025-01-14 12:56:43

您还可以使用ng-include

<div class="col-sm-9 TabContent_container" ng-include="template/custom.html">
</div>

您可以使用“ng-show”来显示隐藏此模板数据。

you can also use ng-include.

<div class="col-sm-9 TabContent_container" ng-include="template/custom.html">
</div>

you can use "ng-show" to show hide this template data.

薔薇婲 2025-01-14 12:56:43

这是解决方案,制作一个像这样的过滤器

.filter('trusted',
   function($sce) {
     return function(ss) {
       return $sce.trustAsHtml(ss)
     };
   }
)

,并将其作为过滤器应用到 ng-bind-html ,就像

<div ng-bind-html="code | trusted">

感谢 Ruben Decrop

here is the solution make a filter like this

.filter('trusted',
   function($sce) {
     return function(ss) {
       return $sce.trustAsHtml(ss)
     };
   }
)

and apply this as a filter to the ng-bind-html like

<div ng-bind-html="code | trusted">

and thank to Ruben Decrop

何以心动 2025-01-14 12:56:43

使用

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

and

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

为此,您需要包含 angular-sanitize.js,
例如在你的 html 文件中

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

Use

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

and

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

For that, you need to include angular-sanitize.js,
for example in your html-file with

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular-sanitize.js"></script>
好久不见√ 2025-01-14 12:56:43

这是一个简单(且不安全)的 bind-as-html 指令,不需要 ngSanitize

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

请注意,如果绑定不受信任,这将引发安全问题内容。

像这样使用:

<div bind-as-html="someHtmlInScope"></div>

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>
北城挽邺 2025-01-14 12:56:43

使用管道在 Angular 4 模板中显示 html 的工作示例。

1.Clated Pipe escape-html.pipe.ts

`

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name : 'keepHtml', pure : false})
export class EscapeHtmlPipe implements PipeTransform{
 constructor(private sanitizer : DomSanitizer){
 }
 transform(content){
  return this.sanitizer.bypassSecurityTrustHtml(content);
 }
}

`
2. 将管道注册到 app.module.ts

 import {EscapeHtmlPipe} from './components/pipes/escape-html.pipe';
    declarations: [...,EscapeHtmlPipe]
  1. 在模板中使用

     
    < /代码>

  2. getDivHtml() { //可以根据要求返回html}

    请在关联的 component.ts 文件中添加适当的 getDivHtml 实现。

Working example with pipe to display html in template with Angular 4.

1.Crated Pipe escape-html.pipe.ts

`

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';
@Pipe({name : 'keepHtml', pure : false})
export class EscapeHtmlPipe implements PipeTransform{
 constructor(private sanitizer : DomSanitizer){
 }
 transform(content){
  return this.sanitizer.bypassSecurityTrustHtml(content);
 }
}

`
2. Register pipe to app.module.ts

 import {EscapeHtmlPipe} from './components/pipes/escape-html.pipe';
    declarations: [...,EscapeHtmlPipe]
  1. Use in your template

        <div class="demoPipe"  [innerHtml]="getDivHtml(obj.header) | keepHtml">

  2. getDivHtml() { //can return html as per requirement}

    Please add appropriate implementation for getDivHtml in associated component.ts file.

浊酒尽余欢 2025-01-14 12:56:43

只需简单地使用[innerHTML],如下所示:

<div [innerHTML]="htmlString"></div>

在您需要使用ng-bind-html之前...

Just simple use [innerHTML], like below:

<div [innerHTML]="htmlString"></div>

Before you needed to use ng-bind-html...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文