Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-18 15:32:03
Original
160 people have browsed it

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"])
Copy after login

3. Use Directive in Template:

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

Example Usage

Controller Object:

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

JSON Response:

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

HTML Output:

<span>Dear John,</span>
Copy after login

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);
                });
            }
        };
    }]);
}());
Copy after login

The above is the detailed content of How to Compile Angular Expressions in Ng-Bind-HTML Directive. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!