[英]Call controller function from HTML dynamically created
I have a controller which have a function called $scope.removePoster
and another one inside the same controller who create a table calling $scope.removePoster
like this: 我有一个控制器,它有一个名为函数$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>';
...
When I add this table in my HTML the button doesn't call this function. 当我在HTML中添加此表时,按钮不会调用此函数。
Sounds like you are using for something like this: 听起来您正在使用类似这样的东西:
<!-- 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;
}
});
};
See, also, this short demo . 另请参见此简短演示 。
Some highlights: 一些重点:
By using ngRepeat
on the <tr>
element, we instruct Angular to create as many tr
elements as necessary based on the content of posters
(subject to the filtering (see below)). 通过使用ngRepeat
的上<tr>
元素,我们指示角来创建任意数量的tr
基于所述内容元素作为必要posters
(受滤波(见下文))。
Angular's built-in limitTo
filter, filter's the posters
array and makes only the first 6 items available to ngRepeat
. Angular的内置limitTo
过滤器,过滤posters
数组,并使ngRepeat
仅可使用前6个项目。 Conviniently enough, when the content of the posters
array changes (eg after removing an entry), the whole expression gets re-evaluated creating or removing DOM nodes as necessary. 足够方便的是,当posters
数组的内容发生更改时(例如,删除条目后),整个表达式将根据需要重新创建或删除DOM节点进行重新评估。
IMPORTANT 重要
The implementation above is not the proper way to handle things in all aspects. 上面的实现并不是处理所有方面的正确方法。 It is the cleanest/easiset way to allow you to wrap your head around Angular's way of building a table dynamically. 这是最干净/轻松的方法,可让您围绕Angular动态构建表的方式进行工作。
Specifically, in a "real-world app", you should have a service bring the data from the server and inject the service into the controller to let it gain access to the data. 具体来说,在“真实世界的应用程序”中,您应该有一个服务,该服务将来自服务器的数据带入服务器,并将该服务注入控制器,以使其能够访问数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.