Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

javascript - 从AngularJS控制器将HTML插入视图(Insert HTML into view from AngularJS controller)

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

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

This comes from a requirement to turn an inconsistent JSON blob into a nested list of id : value pairs.

(这是因为需要将不一致的JSON Blob转换为id : value对的嵌套列表。)

Therefore the HTML is created in the controller and I am now looking to display it.

(因此,在控制器中创建了HTML,现在我希望显示它。)

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

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


Update

(更新资料)

It appears that the problem arises from angular rendering the created HTML as a string within quotes.

(看起来问题出在将创建的HTML角化为引号内的字符串而引起。)

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>
  ask by Swaff translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(对于Angular 1.x,在HTML中使用ng-bind-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.

(此时,您将attempting to use an unsafe value in a safe context错误中attempting to use an unsafe value in a safe context因此您需要使用ngSanitize$ sce来解决该问题。)

$sce($ sce)

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

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

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

ngSanitize(ng消毒)

There are 2 steps:

(分两个步骤:)

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

    (包括angular-sanitize.min.js资源,即:)


    <script src="lib/angular/angular-sanitize.min.js"></script>
  2. In a js file (controller or usually app.js), include ngSanitize, ie:

    (在js文件(控制器或通常为app.js)中,包括ngSanitize,即:)


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...