首頁 > web前端 > js教程 > 如何在 Ng-Bind-HTML 指令中編譯角度表達式

如何在 Ng-Bind-HTML 指令中編譯角度表達式

Barbara Streisand
發布: 2024-10-18 15:32:03
原創
287 人瀏覽過

How to Compile Angular Expressions in Ng-Bind-HTML Directive

AngularJS ng-bind-html: Compiling Angular Code

Introduction

Ng-bind-html directive allows for the dynamic inclusion of HTML code in templates. While it works for basic HTML, angular templates are not interpreted when included. This article provides a solution to compile Angular expressions embedded within ng-bind-html.

Step-by-Step Solution

1. Install Directive:
Install the angular-bind-html-compile directive from GitHub: https://github.com/incuna/angular-bind-html-compile.

2. Include Directive in Module:

angular.module("app", ["angular-bind-html-compile"])
登入後複製

3. Use Directive in Template:

<div bind-html-compile="letterTemplate.content"></div>
登入後複製

Example Usage

Controller Object:

$scope.letter = { user: { name: "John"}}
登入後複製

JSON Response:

{ "letterTemplate":[
    { content: "<span>Dear {{letter.user.name}},</span>" }
]}
登入後複製

HTML Output:

<span>Dear John,</span>
登入後複製

Relevant Directive

(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);
                });
            }
        };
    }]);
}());
登入後複製

以上是如何在 Ng-Bind-HTML 指令中編譯角度表達式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板