Get value in a row on click and pass it to popup

2019-08-26 19:56发布

问题:

I need to get the value in a row of a table on click and display it in popup

HTML:

<md-data-table-container>
    <table md-data-table class="md-primary" md-progress="deferred">
        <thead md-order="query.order" md-trigger="onorderchange">
            <tr>
                <th name="Task To Be Done"></th>
                <th name="Office"></th>
                <th name="Due Date"></th>
            </tr>
        </thead>
        <tbody ng-click="showAlert($event)">
            <tr ng-repeat="dessert in desserts.data" ng-click="showAlert($index)" flex-sm="100" flex-md="100" flex-gt-md="auto">
                <td>{{dessert.task}}</td>
                <td></td>
                <td>{{dessert.due_on}}</td>
            </tr>
        </tbody>
    </table>
</md-data-table-container>

JS:

$scope.desserts = {
    "count": 6,
    "data": [{
        "task": "Frozen yogurt",
        "type": "Ice cream"
    }, {
        "task": "Ice cream sandwich",
        "type": "Ice cream"
    }, {
        "task": "Eclair",
        "type": "Pastry"
    }, {
        "task": "Cupcake",
        "type": "Pastry"
    }, {
        "task": "Jelly bean",
        "type": "Candy"
    }, {
        "task": "Lollipop",
        "type": "Candy"
    }, {
        "task": "Honeycomb",
        "type": "Other"
    }]
};
$scope.showAlert = function (index) {
    $scope.obj = $scope.desserts.data[2];
    $scope.task = $scope.obj.task;
    alert($scope.task);
    console.log($scope.task);
};

issue in my code is that i could get the value on the array which i have specified ".data[2]". Actually when i click a row in my table i need that value to be displayed to popup "sweetAlert". is there any solution

回答1:

Don't pass the $index, as this can be a bit dangerous if the underlying data changes, and in this case it just forces you to re-get the item from the array.

Pass the actual item you want to display back to the alert.

<tr ng-repeat="dessert in desserts.data" ng-click="showAlert(dessert)" flex-sm="100" flex-md="100" flex-gt-md="auto">
                <td>{{dessert.task}}</td>
                <td></td>
                <td>{{dessert.due_on}}</td>
            </tr>

Don't assign to scope unless you really need it elsewhere.

$scope.showAlert = function (dessert) {
   alert('Task:' + dessert.task);
   // if you're just using a variable in this function, declare it locally
   var dessertType = dessert.type;
   console.log(dessertType);
};

See an example of $index causing issues:

http://codeutopia.net/blog/2014/11/10/angularjs-best-practices-avoid-using-ng-repeats-index/comment-page-1/