【问题标题】:AngularJS - Using interpolation in a html templateAngularJS - 在 html 模板中使用插值
【发布时间】:2018-09-26 12:44:35
【问题描述】:

不知道以前是否有人遇到过这种情况,在谷歌上查找我似乎找不到示例。基本上我正在创建一个冗长的 html 模板并将其包装在 ng-bing-html 中,它会加载我的 html 但它不会加载我的插值。让我给你一个简单的例子:

控制器:

$scope.example_text_here = "Hello World!"
$scope.HTML_template = "<p><strong> Example: </strong> {{ example_text_here }}</p>"

HTML:

<div ng-bind-html="HTML_template"></div>

输出

示例: {{ example_text_here }}

我的期望:

示例:世界你好!

有人知道怎么做吗?

【问题讨论】:

标签: javascript html angularjs


【解决方案1】:

您应该使用 $interpolate 模块,然后注入当前作用域甚至 $compile。查看更多https://docs.angularjs.org/api/ng/service/$interpolate

$interpolate($scope.HTML_template)($scope)

【讨论】:

  • 啊,这对我来说是新的,非常有趣的功能。到目前为止似乎工作。非常感谢!
  • 一件很难的小事,ng-bind-html 似乎不起作用。查找此内容,但您知道使用 $interpolate 的正确方法是什么吗?
【解决方案2】:

试试这个

$scope.HTML_template = "<p><strong> Example: 
 </strong>"+$scope.example_text_here+"</p>";

【讨论】:

  • 谢谢,但我也有一个 ng-repeat,不认为这会起作用。
【解决方案3】:

我认为你会使用 AngularJS$sce 服务。

控制器:

angular.module('app', [...])

.controller('myCtrl', function($scope, $sce) {
  ...
  $scope.trustAsHtml = function(params) {
    return $sce.trustAsHtml(params);
  };
  ...
  $scope.example_text_here = "Hello World!";
  $scope.HTML_template = "<p><strong> Example: </strong> {{ example_text_here }}</p>";
  ...
});

标记:

<div ng-bind-html="trustAsHtml(HTML_template)"></div>

现在希望你能得到你的预期结果。谢谢。

【讨论】:

  • 我试试看。
  • 给出相同的结果 {{ example_text_here }}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 2017-07-18
  • 2023-03-10
  • 2018-02-26
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
相关资源
最近更新 更多