Javascript display clicked item from a for loop upon a click event Javascript display clicked item from a for loop upon a click event wordpress wordpress

Javascript display clicked item from a for loop upon a click event


Your ng-click is on the entire list of results, so you have no way of knowing what was clicked. You need it to be on one of the repeated elements, and you need some way to know which one was clicked, like this:

document.getElementById('chickDesc').innerHTML += '<a ng-click="item_clicked(' + i.toString() + ');" class= ...

Define item_clicked in your controller like this:

$scope.item_clicked = function(index) {    $scope.clicked_index = index;    $scope.modal.show();};

Now in your on-modal-shown, remove the for loop and just leave its body, substituting $scope.clicked_index instead of each use of i.

Also, you shouldn't call $http.get('http://dhameergovind.co.za/wp/api/get_posts/') again. It's inefficient, and might also cause you to see the wrong data, in case new posts have been added and the indexes don't match up. Instead, save the data the first time you get it in your success function in on-enter. Something like this:

$scope.posts = data

Optionally, and a bit more advanced, you could make an endpoint like http://dhameergovind.co.za/wp/api/get_posts/{post_id} to get just one post. That would make sure you have the latest data on the post you selected.

As the comment above said, you really aren't using the maximum power of Angular. With Angular, you shouldn't need to use Javascript to build the structure of your page. Writing HTML strings in your Javascript code is a sign that you're doing it wrong. Even manipulating the DOM is probably not the best way. With Angular, your Javascript code should just retrieve, send, and manipulate data, and your template should describe how that's mapped to document structure.

But my answer is the smallest change you can do to your code to make it do what you want.


Why are you looping to display details in your modal? Also you don't need to call your URL again to get data every time you need to show modal window. Just keep the loaded data in a variable and use it for all subsequent clicks.

I assume you are opening the modal window based on user clicking the link. You already defined an id (if you think it is not unique then make it unique) for these links. That id is nothing but index for your array element which needs to be shown on modal window. Just get the array element and set the details to your chickDesc.