2016-04-29 47 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

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