AngularJS 컨트롤러에서보기에 HTML 삽입
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>
Angular 1.x의 ng-bind-html
경우 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
두 단계가 있습니다.
angular-sanitize.min.js 리소스를 포함합니다.
<script src="lib/angular/angular-sanitize.min.js"></script>
js 파일 (controller 또는 일반적으로 app.js)에 ngSanitize를 포함합니다.
angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'ngSanitize'])
다음과 같이 필터를 만들 수도 있습니다.
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 취약성을 나타낼 수 있습니다.
Angular JS는 태그 내에 HTML을 표시합니다.
위의 링크에서 제공된 솔루션이 저에게 효과적이지만이 스레드의 옵션 중 어느 것도 수행하지 않았습니다. AngularJS 버전 1.2.9에서 동일한 것을 찾는 사람
다음은 사본입니다.
좋아, 이것에 대한 해결책을 찾았습니다.
JS :
$scope.renderHtml = function(html_code) { return $sce.trustAsHtml(html_code); };
HTML :
<p ng-bind-html="renderHtml(value.button)"></p>
편집하다:
설정은 다음과 같습니다.
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>
다행히도이 오류 메시지를 피하기 위해 멋진 필터 나 안전하지 않은 방법이 필요하지 않습니다. 이것은 의도하고 안전한 방식으로보기에 HTML 마크 업을 올바르게 출력하기위한 완전한 구현입니다.
Sanitize 모듈은 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 가 답 입니다.
오늘 시도 해봤는데 내가 찾은 유일한 방법은
<div ng-bind-html-unsafe="expression"></div>
ng-bind-html-unsafe
더 이상 작동하지 않습니다.
이것이 가장 짧은 방법입니다.
필터 만들기 :
myApp.filter('unsafe', function($sce) { return $sce.trustAsHtml; });
그리고 당신의 관점에서 :
<div ng-bind-html="customHtml | unsafe"></div>
추신 :이 방법은 ngSanitize
모듈 을 포함 할 필요가 없습니다 .
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);
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.
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.
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()
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
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.
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>
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
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>
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]
Use in your template
<div class="demoPipe" [innerHtml]="getDivHtml(obj.header) | keepHtml">
getDivHtml() { //can return html as per requirement}
Please add appropriate implementation for getDivHtml in associated component.ts file.
Just simple use [innerHTML]
, like below:
<div [innerHTML]="htmlString"></div>
Before you needed to use ng-bind-html
...
In Angular 7 + ionic 4, Html contents can be shown by using "[innerHTML]":
<div [innerHTML]="htmlContent"></div>
I hope, this will also help you. Thanks.
참고URL : https://stackoverflow.com/questions/9381926/insert-html-into-view-from-angularjs-controller
'developer tip' 카테고리의 다른 글
Android Studio에 라이브러리 프로젝트를 어떻게 추가합니까? (0) | 2020.09.29 |
---|---|
목록 무작위 화 (0) | 2020.09.29 |
base64 문자열을 어떻게 인코딩하고 디코딩합니까? (0) | 2020.09.29 |
엄마가 말하지 않은 Vim의 어두운 구석은 무엇입니까? (0) | 2020.09.29 |
Android에서 내 애플리케이션의 메모리 사용량을 어떻게 확인합니까? (0) | 2020.09.29 |