3 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超3個(gè)贊
不是一個(gè)完美的修復(fù),仍然! - 只是為了展示如何進(jìn)行動(dòng)態(tài)編譯
app.controller('AppController', function ($scope, $compile) {
var $el = $('<td contenteditable><input type="text" class="editBox" value=""/></td>' +
'<td contenteditable><input type="text" class="editBox" value=""/></td>' +
'<td>' +
'<span>' +
'<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>' +
'</span>' +
'</td>').appendTo('#newTransaction');
$compile($el)($scope);
$scope.create = function(){
console.log('clicked')
}
})
不要使用控制器進(jìn)行dom操作 - 它必須在指令的幫助下完成

TA貢獻(xiàn)1886條經(jīng)驗(yàn) 獲得超2個(gè)贊
為了使用ng-click,我們需要使用服務(wù)來編譯這個(gè)源代碼$compile。Angular應(yīng)該知道新生成的HTML,因此應(yīng)該將此HTML包含在摘要周期中以便觸發(fā)ng-click和其他事件。
看到 Fiddle
創(chuàng)建“compilator”:
.directive( 'compileData', function ( $compile ) {
return {
scope: true,
link: function ( scope, element, attrs ) {
var elmnt;
attrs.$observe( 'template', function ( myTemplate ) {
if ( angular.isDefined( myTemplate ) ) {
// compile the provided template against the current scope
elmnt = $compile( myTemplate )( scope );
element.html(""); // dummy "clear"
element.append( elmnt );
}
});
}
};
});
之后,創(chuàng)建factory模擬你追加的假人:
.factory( 'tempService', function () {
return function () {
return '<td contenteditable><input type="text" class="editBox" value=""/></td>'+
'<td contenteditable><input type="text" class="editBox" value=""/></td>'+
'<td>'+
'<span>'+
'<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>'+
'</span>'+
'</td>';
};
});
最后稱之為:
<div compile-data template="{{mainPage}}"></div>
在控制器中:
$scope.newTransaction= tempService();
對(duì)于你的例子應(yīng)該是這樣的:
<table data-ng-table="tableParams" class="table table-bordered table-hover " style="border-collapse:collapse" data-ng-init="host.editSave = false" >
<tr compile-data template="{{newTransaction}}">
</tr>
<tr data-ng-repeat="host in hosts|filter:search:strict" >
<td class="hostTableCols" data-ng-hide="host.editSave">{{host.hostCd}}</td>
<td class="hostTableCols" data-ng-hide="host.editSave">{{host.hostName}}</td>
</tr>
</table>
BTW,現(xiàn)在你可以在你的代碼上使用相同的指令并編譯任何動(dòng)態(tài)HTML。

TA貢獻(xiàn)1805條經(jīng)驗(yàn) 獲得超10個(gè)贊
您可以在angular.element(this).scope()不使用ng-click的情況下使用
并改變
'<button id="createHost" class="btn btn-mini btn-success" data-ng-click="create()"><b>Create</b></button>'
至
'<button id="createHost" class="btn btn-mini btn-success" onclick="angular.element(this).scope().create()"><b>Create</b></button>' 很好
添加回答
舉報(bào)