html button inside ng-repeat is not working

2019-06-07 15:20发布

问题:

I'm trying to import a list of customers, and I want to proceed to a personalized customer page with specific information about a customer (using function showit). I currently have this:

<table ng-controller="patientsCtrl" class="table-responsive" class="fixed">                     
        <thead>
            <th>ID</th>
            <th>Name</th>
            <th>Policy Nr</th>
            <th>Pol. Type</th>
            <th>Check</th>
        </thead>
        <tbody>
            <tr ng-repeat="p in patients | orderBy:'patID'">
            <td>{{ p.patID }}</td>
            <td>{{ p.name }}</td>
            <td>{{ p.policy_number }}</td>
            <td>{{ p.policy_type }}</td>
            <td> <button ng-click="showit(p.name)">check</button> </td>
        </tbody>
</table>

回答1:

Just pretend that it's written <button ng-click="vari=true">check</button> . the button is not working when inside the table (the function phase I will implement later)

You have a scoping issue. The button is working inside the table but the data is not getting outside the table because of the scope hierarchy.

<div ng-controller="patientsCtrl">
    <p>{{vari}}</p>
    <table class="table-responsive" class="fixed">                     
        <thead>
            <th>ID</th>
            <th>Name</th>
            <th>Policy Nr</th>
            <th>Pol. Type</th>
            <th>Check</th>
        </thead>
        <tbody>
            <tr ng-repeat="p in patients | orderBy:'patID'">
            <td>{{ p.patID }}</td>
            <td>{{ p.name }}</td>
            <td>{{ p.policy_number }}</td>
            <td>{{ p.policy_type }}</td>
            <td> <button ng-click="$parent.vari=true">check</button> </td>
        </tbody>
    </table>
    <p>{{vari}}</p>
</div>

ng-repeat creates a scope for each item in a collection. To put data on the controller's scope, use $parent.

From the Docs:

The ngRepeat directive instantiates a template once per item from a collection. Each template instance gets its own scope, where the given loop variable is set to the current collection item, and $index is set to the item index or key.

-- https://docs.angularjs.org/api/ng/directive/ngRepeat