【问题标题】:How do I insert html code using ng-repeat in AngularJS?如何在 AngularJS 中使用 ng-repeat 插入 html 代码?
【发布时间】:2016-08-23 23:24:13
【问题描述】:

我想使用 ng-repeat 在 div 中创建一行按钮。然后以某种方式克隆/复制该 div。

基本上是这样的;

[0][0][0][0]

我还想制作下面重复的 div。我之前使用过 clone,但我需要使用 ng-repeat 并且没有那么成功。

<body ng-app="myApp" ng-controller="myCtrl">
...
...
...
<div id="boxHolder">
<span id="musicBox" ng-repeat="x in instrumentBtns">
{{x}}
</span>
</div>

这就是我的 html 文件。到目前为止,我的 app.js 文件看起来像这样。

var app = angular.module("myApp", []);

app.controller("myCtrl", function($scope) {
  $scope.instrumentBtns = [
    '<button id="inst0">0</button>',
    '<button id="inst1">0</button>',
    '<button id="inst2">0</button>',
    '<button id="inst3">0</button>',
  ]
});

第一次发帖到 StackOverflow,所以如果我不清楚,请告诉我!谢谢!

【问题讨论】:

  • 为什么不在重复范围内模板化按钮,并根据需要插入动态参数?例如。 &lt;span ng-repeat="x in instrumentBtns"&gt;&lt;button ng-attr-id="{{'instr' + x}}"&gt;0&lt;/button&gt;&lt;/span&gt;
  • 因为我不知道这是一种可能性,但它确实有效!我对这一切都很陌生,非常感谢!它究竟是如何工作的?
  • 没问题! Angular 有点让人头疼。这都是 Angular 的interpolation 的一部分。它在您的视图中使用前缀属性,并将它们解释为 Angular expressions。这使您不仅可以使用角度来操作页面上的文本,而且不必将逻辑放入控制器中。它比这更复杂,但我只能在评论中写下这么多。如果您想了解更多详细信息,请随时直接与我联系。 (电子邮件在个人资料中)

标签: javascript html angularjs angularjs-ng-repeat ng-repeat


【解决方案1】:

使用ngSanitize

angular.module('sanitizeExample', ['ngSanitize'])
           .controller('ExampleController', ['$scope', '$sce', function($scope, $sce) {
  $scope.htmlTrusted = function(html) {
    return $sce.trustAsHtml(html);
  }
}]);

<span id="musicBox" ng-repeat="x in instrumentBtns">
  <div ng-bind-html="htmlTrusted(x)"></div>
</span>

【讨论】:

  • 这绝对是一个很好的答案,尤其是当您从不受信任的来源加载 HTML 时。 (用户输入/参数)任何信息安全人员都会告诉你,永远不要相信客户。
  • 当然.. 小心使用! ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
相关资源
最近更新 更多