我有一個應用程序,我需要創建html並將其添加到對象數組。這個html應該被輸出到頁面中。夠簡單。但是,我還需要使html響應用戶操作(點擊),在這種情況下,angular需要我使用$ compile來創建角化模板。
查看Plunkr。在這個例子中,應該發生的事情是,當你點擊其中一個按鈕時,將會在對象中嵌入html代碼生成一個彈出窗口,您可以在JSON輸出中看到該代碼。
只要我這樣做,我得到的錯誤轉換爲JSON循環結構。如果我不這樣做,則不會調用ng-click =「Go()」。
SCRIPT
var template = "<ul class='unstyled'>" +
"<li ng-click='go()' style='background-color:lightcyan;'><ul class='inline'><li>1...</li><li>1...</li></ul></li>" +
"<li ng-click='go()'><ul class='inline'><li>1...</li><li>1...</li></ul></li>" +
"<li ng-click='go()' style='background-color:lightcyan;'><ul class='inline'><li>1...</li><li>1...</li></ul></li>" +
"</ul>";
// template = $compile(template)($scope);
$scope.data = [
{"id": 1, "html": template},
{"id": 2, "html": template}
];
$scope.go = function() {
alert('It works');
};
$scope.openPopin = function (html) {
var e = window.event;
var popin = document.getElementById('popin');
var innerdiv = document.getElementById('innerdiv').innerHTML=html;
popin.style.top= e.pageY - 20+"px";
popin.style.left = e.pageX - 20+"px";
popin.style.marginLeft = -500+"px";
popin.style.marginTop = -100+"px";
};
$scope.closePopin = function() {
var popin = document.getElementById('popin');
popin.style.top = -500+"px";
popin.style.left = -500+"px";
};
HTML
<div class="popin grey-border" id="popin">
<button class="close" ng-click="closePopin()">×</button>
<div id="innerdiv"></div>
</div>
<pre>{{ data |json }} </pre>
<br/>
<table style="float: right;">
<tr ng-repeat="d in data" id="{{$index}}">
<td>{{ d.id }} -
<button class="btn btn-mini btn-info" ng-click="openPopin(d.html)"><i class="icon-info-sign"></i></button>
</td>
</tr>
</table>
如果我嘗試一下plunker,我會得到一個不同的錯誤:'錯誤:e是undefined'。 (使用FF 26)可能是一個跨瀏覽器兼容性問題。 – towr