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

时间:2015-11-16 09:01:46

标签: angularjs angular-material

我需要在点击的一行中获取值并在弹出窗口中显示

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);
};
我的代码中的问题是我可以获得我指定的数组的值&#34; .data [2]&#34;。实际上,当我点击表格中的一行时,我需要将该值显示为popup&#34; sweetAlert&#34;。有没有解决方案

1 个答案:

答案 0 :(得分:3)

不要通过$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/