데이터베이스에서 동적 HTML 문자열 컴파일 중
상황
Angular 앱에는 컨트롤러에 의해 지원되는 Page라는 명령어가 중첩되어 있으며 ng-bind-html-unsafe 속성을 가진 div가 포함되어 있습니다.이것은 'pageContent'라는 $scope var에 할당됩니다.이 변수는 데이터베이스에서 동적으로 생성된 HTML을 할당합니다.사용자가 다음 페이지로 넘어가면 DB로 호출되고 pageContent var가 이 새로운 HTML로 설정됩니다.이 HTML은 ng-bind-html-unsafe를 통해 화면에 렌더링됩니다.코드는 다음과 같습니다.
페이지 지시문
angular.module('myApp.directives')
.directive('myPage', function ($compile) {
return {
templateUrl: 'page.html',
restrict: 'E',
compile: function compile(element, attrs, transclude) {
// does nothing currently
return {
pre: function preLink(scope, element, attrs, controller) {
// does nothing currently
},
post: function postLink(scope, element, attrs, controller) {
// does nothing currently
}
}
}
};
});
페이지 디렉티브의 템플릿("위의 templateUrl 속성에서 page.html")
<div ng-controller="PageCtrl" >
...
<!-- dynamic page content written into the div below -->
<div ng-bind-html-unsafe="pageContent" >
...
</div>
페이지 컨트롤러
angular.module('myApp')
.controller('PageCtrl', function ($scope) {
$scope.pageContent = '';
$scope.$on( "receivedPageContent", function(event, args) {
console.log( 'new page content received after DB call' );
$scope.pageContent = args.htmlStrFromDB;
});
});
됐다.브라우저에서 올바르게 렌더링된 DB에서 페이지의 HTML을 볼 수 있습니다.사용자가 다음 페이지로 이동하면 다음 페이지의 내용이 표시됩니다.아직까지는 좋아.
문제
여기서의 문제는 페이지 콘텐츠 안에 인터랙티브한 콘텐츠를 포함시키고 싶다는 것입니다.예를 들어 HTML에는 사용자가 클릭하면 팝업모달 창을 표시하는 등 Angular가 멋진 작업을 수행해야 하는 섬네일 이미지가 포함되어 있을 수 있습니다.데이터베이스의 HTML 문자열에 Angular 메서드 호출(ng-click)을 넣었습니다만, 물론 Angular는 HTML 문자열을 해석하여 인식하고 컴파일하지 않는 한 메서드 호출과 디렉티브를 인식하지 않습니다.
델의 데이터베이스
페이지 1의 내용:
<p>Here's a cool pic of a lion. <img src="lion.png" ng-click="doSomethingAwesone('lion', 'showImage')" > Click on him to see a large image.</p>
2페이지의 내용:
<p>Here's a snake. <img src="snake.png" ng-click="doSomethingAwesone('snake', 'playSound')" >Click to make him hiss.</p>
페이지 컨트롤러로 돌아가 대응하는 $scope 함수를 추가합니다.
페이지 컨트롤러
$scope.doSomethingAwesome = function( id, action ) {
console.log( "Going to do " + action + " with "+ id );
}
DB의 HTML 문자열 내에서 'doSomethingAwesome' 메서드를 어떻게 불러야 할지 모르겠습니다.Angular가 HTML 문자열을 해석해야 한다는 건 알지만, 어떻게요?$compile 서비스에 대한 애매한 중얼거림을 읽고 몇 가지 예를 복사해서 붙여 넣었지만 효과가 없었습니다.또, 대부분의 예에서는, 디렉티브의 링크 단계중에만 다이내믹 컨텐츠가 설정되어 있는 것을 나타내고 있습니다.우리는 페이지가 앱의 수명 내내 살아있기를 바란다.사용자가 페이지를 넘길 때 새로운 콘텐츠를 지속적으로 수신, 컴파일 및 표시합니다.
추상적인 의미에서 Angular 앱에 Angular의 청크를 동적으로 중첩하고 있으며, 이를 서로 교환할 수 있어야 한다고 할 수 있습니다.
저는 Angular 문서의 다양한 부분과 모든 종류의 블로그 게시물을 여러 번 읽었고 JS Fiddle은 사람들의 코드를 다루었습니다.내가 앵글을 완전히 오해하고 있는 건지, 아니면 간단한 걸 놓치고 있는 건지, 아니면 내가 느린 건지 모르겠어.어쨌든 조언이 좀 필요하겠네요.
ng-bind-html-unsafe
HTML을 사용하다앵귤러 에 angular에에 DOM angular angular 。 쓰셔야 돼요.$compile
서비스를 제공하고 있습니다.이 플런커는 사용법을 시연하기 위해 만들었습니다.$compile
사용자가 입력하고 컨트롤러 범위에 바인딩하는 디렉티브 렌더링 동적 HTML을 만듭니다.을 사용하다
demo.demo.demo
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="angular.js@1.0.7" data-semver="1.0.7" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body>
<h1>Compile dynamic HTML</h1>
<div ng-controller="MyController">
<textarea ng-model="html"></textarea>
<div dynamic="html"></div>
</div>
</body>
</html>
script.discripts.discripts: 스크립트
var app = angular.module('app', []);
app.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
link: function (scope, ele, attrs) {
scope.$watch(attrs.dynamic, function(html) {
ele.html(html);
$compile(ele.contents())(scope);
});
}
};
});
function MyController($scope) {
$scope.click = function(arg) {
alert('Clicked ' + arg);
}
$scope.html = '<a ng-click="click(1)" href="#">Click me</a>';
}
1.2의 경우 1.2.10 은 다음과 같습니다.scope.$watch(attrs.dynamic, function(html) {
는 무효 하고 있었습니다.은, 「 문자 」의 있었기 때문입니다.그 이유는 값을 감시하려고 했기 때문입니다.attrs.dynamic
texthtml 입니다.
스코프 속성에서 속성을 가져와 수정했습니다.
scope: { dynamic: '=dynamic'},
나의 예
angular.module('app')
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'dynamic' , function(html){
element.html(html);
$compile(element.contents())(scope);
});
}
};
});
Google 토론 그룹에 있습니다.저는 좋아요.
var $injector = angular.injector(['ng', 'myApp']);
$injector.invoke(function($rootScope, $compile) {
$compile(element)($rootScope);
});
사용할 수 있습니다.
ng-timeout-http://https://docs.angularjs.org/api/ng/service/$sce
html을 동적으로 바인드하는 디렉티브.단, $sce 서비스를 통해 데이터를 받아야 합니다.
http://plnkr.co/edit/k4s3Bx에서 라이브 데모를 보실 수 있습니다.
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
$scope.getHtml=function(){
return $sce.trustAsHtml("<b>Hi Rupesh hi <u>dfdfdfdf</u>!</b>sdafsdfsdf<button>dfdfasdf</button>");
}
});
<body ng-controller="MainCtrl">
<span ng-bind-html="getHtml()"></span>
</body>
아래 코드를 사용하여 html을 바인딩해 보십시오.
.directive('dynamic', function ($compile) {
return {
restrict: 'A',
replace: true,
scope: { dynamic: '=dynamic'},
link: function postLink(scope, element, attrs) {
scope.$watch( 'attrs.dynamic' , function(html){
element.html(scope.dynamic);
$compile(element.contents())(scope);
});
}
};
});
element.html(attr.dynamic)보다 이 요소.html(scope.dynamic)를 시험합니다.
언급URL : https://stackoverflow.com/questions/18157305/compiling-dynamic-html-strings-from-database
'programing' 카테고리의 다른 글
Http Only cookie는 AJAX 요청에서 어떻게 작동합니까? (0) | 2023.03.08 |
---|---|
HTML을 각도 지시어에 전달하려면 어떻게 해야 합니까? (0) | 2023.03.08 |
meta_query를 사용한 복잡한 custom_field 검색 (0) | 2023.03.08 |
requirejs를 사용하여 정적 JSON 파일을 로드하려면 어떻게 해야 합니까? (0) | 2023.03.08 |
mvn spring-boot: run vs java - jar (0) | 2023.03.08 |