在JavaScript中获取数组中选定值的最佳做法

时间:2019-01-24 09:28:15

标签: javascript angularjs

在这种情况下,我想知道哪种方法是一种好的做法: 假设我有一个数据表($ scope.alarms变量),并且需要在我的应用程序中跟踪从该表中选择的行。

<script>
    angular.module('app').controller('AlarmController', ['$scope', function($scope){
        $scope.selected_alarms = [];
        var data = [
            {id: 0, name: "data1"},
            {id: 1, name: "data2"},
            {id: 2, name: "data3"},
        ];
        $scope.alarms = data.map((obj) => {
             obj['checked'] = false;
             return obj;
        });
    }]);
</script>

最好在选择行时将选定的行数据推入数组,并在取消选择该行时将其从数组中切出,例如以下代码:

<tr ng-controller="AlarmController" ng-repeat="alarm in alarms">
    <td><input type="checkbox" ng-model="alarm.checked" /></td>
    <td ng-click="control_alarm(alarm)">{{alarm.id}}</td>
    <td ng-click="control_alarm(alarm)">{{alarm.name}}</td>
    <td>
        <div class="col-edit" ng-click="get_selected_alarm(alarm)"></div>
    </td>
</tr>
<script>

    $scope.control_alarm = (alarm) => {
        if(alarm.checked){
            $scope.selected_alarms.push(alarm);
        }
        else{
            var index = $scope.selected_alarms.findIndex(obj => obj.id === alarm.id)
            $scope.selected_alarms.splice(index, 1);
        }
    };
    $scope.get_selected_alarm = () => {
        console.log($scope.selected_alarms);
    };
</script>

或者当我想像这样使用数据表中的选定数据时,最好操纵原始数据表并更改选定的行状态并创建循环:

<tr ng-controller="AlarmController" ng-repeat="alarm in alarms">
    <td><input type="checkbox" ng-model="alarm.checked" /></td>
    <td ng-click="alarm.checked = !alarm.checked">{{alarm.id}}</td>
    <td ng-click="alarm.checked = !alarm.checked">{{alarm.name}}</td>
    <td>
        <div class="col-edit" ng-click="get_selected_alarm(alarm)"></div>
    </td>
</tr>
<script>
    $scope.get_selected_alarm = () => {
        var selected_alarms = $scope.alarms.filter(obj => obj.checked);
    };
</script>

我想知道考虑角度js性能和干净代码角度的情况下,在行数较多的情况下哪种方法更好。

0 个答案:

没有答案