单击时连续获取值并将其传递给弹出窗口

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

我需要在单击时获取 table 行中的值并在弹出窗口中显示它

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);
};

我的代码中的问题是我可以获取指定“.data[2]”的数组的值。实际上,当我单击 table 中的一行时,我需要将该值显示到弹出窗口 "sweetAlert"。有什么解决办法吗

不要传递 $index,因为如果基础数据发生变化,这可能会有点危险,在这种情况下,它只会强制您从数组中重新获取项目。

将您要显示的实际项目传回警报。

<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>

除非你真的在其他地方需要它,否则不要分配给范围。

$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);
};

查看导致问题的 $index 示例:

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