[英]Call controller function from HTML dynamically created
我有一個控制器,它有一個名為函數$scope.removePoster
和另外一個誰創建表調用同一個控制器內$scope.removePoster
是這樣的:
for(var i=0; i < 6 && postersNum >= 0; i++){
...
table += '<td align="center">';
table += '<img width="150" height="175" src="../js/librerias/carousel/images/'+$scope.posters[indexPosters]['image']+'"><br>';
table += '<button type="button" class="btn btn-danger" ng-click="removePoster('+$scope.posters[indexPosters]['id']+')">Delete</button>';
table += '</td>';
...
當我在HTML中添加此表時,按鈕不會調用此函數。
聽起來您正在使用類似這樣的東西:
<!-- HTML -->
<table>
<tr ng-repeat="poster in posters | limitTo: 6">
<td align="center">
Poster {{poster.id}}
<img width="15" height="18"
ng-src="../js/librerias/carousel/images/{{poster.image}}" />
<button type="button" class="btn btn-danger"
ng-click="removePoster(poster.id)">
Delete
</button>
</td>
</tr>
</table>
// Controller:
$scope.posters = [];
$scope.getPosters = function (url) {
$http.post(url, {'method' : 1}).success(function (data, status) {
$scope.posters = data;
});
};
$scope.removePoster = function (id) {
$scope.posters.some(function (poster, idx) {
if (poster.id === id) {
$scope.posters.splice(idx, 1);
return true;
}
});
};
另請參見此簡短演示 。
一些重點:
通過使用ngRepeat
的上<tr>
元素,我們指示角來創建任意數量的tr
基於所述內容元素作為必要posters
(受濾波(見下文))。
Angular的內置limitTo
過濾器,過濾posters
數組,並使ngRepeat
僅可使用前6個項目。 足夠方便的是,當posters
數組的內容發生更改時(例如,刪除條目后),整個表達式將根據需要重新創建或刪除DOM節點進行重新評估。
重要
上面的實現並不是處理所有方面的正確方法。 這是最干凈/輕松的方法,可讓您圍繞Angular動態構建表的方式進行工作。
具體來說,在“真實世界的應用程序”中,您應該有一個服務,該服務將來自服務器的數據帶入服務器,並將該服務注入控制器,以使其能夠訪問數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.