How to show the details of a particular row in a modal when row is clicked in AngularJS

I'm new to AngularJS. I'm converting some pages to AngularJS. I just displayed rows of information. However I'm having trouble converting the button onclick part to AngularJS. Can someone please help me. Below is the code that I'm working with.

<div ng-repeat="i in data">
 <p>{{i.name}}</p>
<button class="btn btn-xs btn-default" data-toggle="modal" data-target=".show-ticket-details-modal" onclick="show_details(10)">
          <i class="fa fa-info"></i>
        </button>
</div>

Answers 1

  • Try using ng-click (https://docs.angularjs.org/api/ng/directive/ngClick). This runs a function in your angular controller when you click an element. All you've got to do is add the ng-click directive to your element, and then build a function with the same name in your angular controller to handle the data.

    IE, replace onclick="show_details(10)" with: ng-click="show_details(10)".

    Then, in your controller, build a function with the same name that will handle the data show_details(10), like:

    $scope.show_details = function(index) { 
        console.log(index); // will log 10 in the example above
        // do stuff with your index here, 
        // pass data to your angular factory, etc.
    };
    

    Note: For <form> elements, you can use the ng-submit directive instead (https://docs.angularjs.org/api/ng/directive/ngSubmit). Just use ng-submit="someFunction()" instead of ng-click.

    Another Idea:

    Instead of passing in the number 10, you could also use track by $index (https://docs.angularjs.org/api/ng/directive/ngRepeat#), for example, in your ng-repeat, you could:

    ng-repeat="i in data track by $index"
    

    Now, you can actually just pass $index into your ng-click function, instead of the number 10:

    ng-click="show_details($index)" // $index will be 10, if the index of `i` was 10 in `data`
    

    Hope this helps somewhat, let me know if you have any questions! The links included show more examples of their usage!


Related Articles