programing

ng-bind-html의 angularjs 코드 컴파일 방법

easyjava 2023. 3. 20. 23:42
반응형

ng-bind-html의 angularjs 코드 컴파일 방법

저는 angularjs 1.2.0-rc.3을 사용하고 있습니다.HTML 코드를 템플릿에 동적으로 포함시키고 싶습니다.이를 위해 컨트롤러에서 다음을 사용합니다.

html = "<div>hello</div>";
$scope.unicTabContent = $sce.trustAsHtml(html);

템플릿에는 다음과 같은 내용이 있습니다.

<div id="unicTab" ng-bind-html="unicTabContent"></div>

일반 html 코드에서는 정상적으로 동작합니다.그러나 앵글 템플릿을 넣으려고 하면 해석되지 않고 페이지에만 포함되어 있습니다.예를 들어, 다음을 포함합니다.

<div ng-controller="formCtrl">
    <div ng-repeat="item in content" ng-init="init()">
    </div>
</div>

정말 감사해요.

이 솔루션에서는 하드코드 템플릿을 사용하지 않으며 API 응답에 포함된 Angular 식을 컴파일할 수 있습니다.


스텝 1. 다음 디렉티브를 설치합니다.https://github.com/incuna/angular-bind-html-compile

스텝 2. 모듈에 지시문을 포함합니다.

angular.module("app", ["angular-bind-html-compile"])

스텝 3. 템플릿의 지시어를 사용합니다.

<div bind-html-compile="letterTemplate.content"></div>

결과:

컨트롤러 오브젝트

 $scope.letter = { user: { name: "John"}}

JSON 응답

{ "letterTemplate":[
    { content: "<span>Dear {{letter.user.name}},</span>" }
]}

HTML 출력 =

<div bind-html-compile="letterTemplate.content"> 
   <span>Dear John,</span>
</div>

참고로, 관련 지시는 다음과 같습니다.

(function () {
    'use strict';

    var module = angular.module('angular-bind-html-compile', []);

    module.directive('bindHtmlCompile', ['$compile', function ($compile) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                scope.$watch(function () {
                    return scope.$eval(attrs.bindHtmlCompile);
                }, function (value) {
                    element.html(value);
                    $compile(element.contents())(scope);
                });
            }
        };
    }]);
}());

이게 제가 만든 겁니다. 각진TM 방식인지 모르겠지만 작동도 하고 아주 간단합니다.

.directive('dynamic', function($compile) {
    return {
        restrict: 'A',
        replace: true,
        link: function (scope, element, attrs) {
            scope.$watch(attrs.dynamic, function(html) {
                $compile(element.html(html).contents())(scope);
            });
        }
    };
});

그러니까.

<div id="unicTab" dynamic="unicTabContent"></div>

편집: 각진 방법을 찾았는데, 매우 간단합니다.

$templateCache.put('unicTabContent', $sce.trustAsHtml(html));
<div id="unicTab" ng-include="'unicTabContent'"></div>

직접 지시 같은 건 할 필요 없어그러나 이것은 바인드 원스 방식의 거래커스텀 디렉티브처럼 html에 변경이 가해지는 을 볼 수 없습니다.

Vinod Louis가 코멘트에서 말한 것처럼 가장 좋은 방법은 템플릿을 사용하는 것이었습니다.예를 들어 index.html 내에 해당 코드를 추가하는 등 일반 코드 외부에 템플릿을 정의해야 했습니다.

<script type="text/ng-template" id="unic_tab_template.html">
    <div ng-switch on="page">
        <div ng-switch-when="home"><p>{{home}}</p></div>
        <div ng-switch-when="form">
            <div ng-controller="formCtrl">
                <div ng-repeat="item in content">{{item.name}}:{{item.value}}</div>
            </div>
        </div>
        <div ng-switch-default>an error accured</div>
    </div>
</script>

이 템플릿은 조건부이므로 $scope.page 값에 따라 3개의 템플릿(세 번째 템플릿은 오류 핸들러) 간에 전환됩니다.그것을 사용하기 위해 나는 다음과 같이 했다.

<div id="unicTab" ng-controller="unicTabCtrl">
    <div ng-include="'unic_tab_template.html'"></div>
</div>

이와 같이 내 페이지는 unicTabCtrl 컨트롤러의 $scope에 따라 달라집니다.

결론적으로 angularsjs 템플릿 심을 삽입하는 것은 실현하기 어렵지만(컴파일 심이 해결책이지만, 나는 그것을 실행할 수 없었다.대신 조건부 템플리트를 사용할 수 있습니다.

저도 같은 일을 하려고 하다가 우연히 이 모듈을 발견했습니다.

http://ngmodules.org/modules/ng-html-compile

그냥 넣었더니 'ng-bind-html'이 아니라 'ng-html-compile'을 사용할 수 있게 되었습니다.

템플릿을 사용하지 않고 현재 앱에서 유사한 문제를 해결하는 방법(고상하지는 않지만 작동):

directive('ngBindHtmlCompile', ['$compile', function ($compile) {
    return {
        restrict: 'A',
        compile: function compile(tElement, tAttributes, transcludeFn) {
            return function postLink(scope, element, attributes) {
                scope.$watch(function() {
                    return scope.$eval(attributes.ngBindHtml);
                }, function(newValue, oldValue) {
                    $compile(element.children())(scope);
                });
            };
        }
    };
}]);

그것은 필요하다ngBindHtml에 따라 변경 후 요소 내용을 컴파일합니다.ngBindHtml.

<div id="unicTab" ng-bind-html="unicTabContent" ng-bind-html-compile></div>

ng-html-compile비슷해 보이지만 템플릿 내용이 변경되면 언뜻 재계산되지 않습니다.근데 안 먹어봤어요.

한 가지 방법은 각도 식을 포함하는 사용자 지정 템플릿을 삽입하기 위한 지시문을 사용하는 것입니다.

<div id="unicTab" unic-tab-content></div>
app.directive("unicTabContent",function(){
   return {
      restrict:"A",
      template:'{{unicTabContent}}'
   }
})

아래 코드는 Angular에 내장된 $in interpolate 및 $sce 객체를 사용하는 것이 훨씬 간단합니다.먼저 지시문에서 필요한 커스텀을 수행할 때 지시문에 $interpolate 및 $sce Angular 객체를 삽입합니다.

amqApp.directive('myDir', ['$interpolate', '$sce', function ($interpolate,$sce ) {...}

그런 다음 가져온 html 식에 있는 모든 범위 변수를 만듭니다.

$scope.custom = 'Hello World';

다음으로 $interpolate를 사용하여 커스텀HTML과 그 식을 처리합니다.바인드하기 전에 $sce 객체를 사용하여 HTML로 신뢰하는 것을 확인합니다.

var html = $interpolate('<b>{{custom}}</b>')($scope);    
$scope.data = $sce.trustAsHtml(html);

마지막으로 뷰에서는 뷰 디스플레이에 "ng-bind" 또는 "ng-bind-html"이 표시된 요소를 사용합니다.$sce piece는 html 템플릿에 이렇게 바인드하지 않으면 HTML(텍스트로 인식)로 표시되지 않는다는 것을 알았습니다.

<span ng-bind-html="data"></span>

굵은 글씨로...

안녕 세계

이 트릭을 사용하여 web.config에서 커스텀 각도 {{expressions}}의 텍스트/HTML을 Import했습니다.

빌트인 템플릿을 기반으로 한 @clement-roblot의 매우 심플한 솔루션.

컨트롤러:

app.controller('TestCtrl', [
    '$scope',
    '$templateCache',
    function ($scope, $templateCache) {
        $templateCache.put('test.html', '2 + 2 = {{ 2 + 2 }}');
    }
]);

표시:

<div ng-include="'test.html'"></div>

언급URL : https://stackoverflow.com/questions/19726179/how-to-make-ng-bind-html-compile-angularjs-code

반응형