2016-04-29 46 views
5

我想使用ng-repeat在div中创建一排按钮。然后将该div以某种方式克隆/复制。如何在AngularJS中使用ng-repeat插入html代码?

基本上它会看起来像这样;

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

而且我也很希望做出的div是在下面重复。我之前使用过克隆,但我需要使用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,所以如果我不清楚请让我知道!谢谢!

+2

为什么不模板按钮重复跨度内,并且只需要插入动态参数的需要?例如。 '

+1

因为我不知道这是一种可能性,但有用!我对这一切都很陌生,非常感谢!它究竟如何工作? –

+0

不是问题! Angular有点野兽来包裹你的头。这是Angular [插入](https://docs.angularjs.org/guide/interpolation)的一部分。它在视图中使用前缀属性,并将它们解释为Angular [表达式](https://docs.angularjs.org/guide/expression)。这使您可以用角度操纵页面上的文本,而不必将逻辑放入控制器。这比这更复杂,但我只能写评论。如果你想了解更多的细节,请随时与我联系。 (电子邮件的档案) –

回答

4

使用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> 
+0

这绝对是一个很好的答案,特别是如果你从不受信任的来源加载HTML。 (用户输入/参数)任何信息安全人员都会告诉你,永远不要相信客户。 –

+1

当然..小心使用! ;) –