简体   繁体   中英

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:

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.

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:

  1. 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)).

  2. Angular's built-in limitTo filter, filter's the posters array and makes only the first 6 items available to ngRepeat . 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.


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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM