如何使ng-bind-html编译angularjs代码

如何使ng-bind-html编译angularjs代码,第1张

如何使ng-bind-html编译angularjs代码

此解决方案不使用硬编码模板,您可以编译嵌入在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);     }); }        };    }]);}());


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5509273.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-13
下一篇 2022-12-13

发表评论

登录后才能评论

评论列表(0条)

保存