Esteban Verbel
Esteban Verbel

Reputation: 738

How to pass an id from view(HTML) to an AngularJs controller when onclick event is triggered?

I am building an application using ASP.NET and AngularJs. I am trying to pass object id from the view (HTML) to the Angular controller, to then make an http call to the api. I don't know how to pass the id of an specific object from this table when the delete link is clicked.

<table class="table table-responsive table-striped">
        <tr ng-repeat="post in viewModel.posts">

            <td>{{ post.text }}</td>
            <td>{{ post.postedOn | date:'medium' }}</td>
            <td><a href="#" class="btn btn-sm">Edit</a></td>

            <td><a ng-click="viewModel.deletePost" class="btn btn-sm">Delete</a></td> 

        </tr>
</table>

and this is how I am trying to make the call to the API from the controller

// delete post function
viewModel.deletePost = function () {

        viewModel.errorMessage = "";

        $http.delete("http://localhost:61878/api/posts", viewModel.newPost.id)
            .then(function (response) {

                // sucess delete
                viewModel.posts.delete(response.data);

                viewModel.newPost = {};

            }, function () {
                // failed to delete

                viewModel.errorMessage = "Failed to delete post"
            })
            .finally(function () {

            });
    };

Does anybody know how can I pass the id of the respective post on the row clicked to the Angular controller?

Upvotes: 3

Views: 2708

Answers (1)

John Smith
John Smith

Reputation: 2341

viewModel.deletePost is a function - just call it with parameters.

<a ng-click="viewModel.deletePost(post.id)" class="btn btn-sm">Delete</a>

After that you just have to add the parameter to the function:

viewModel.deletePost = function (id) { ... }

Upvotes: 4

Related Questions