计数类别项目算法与插入新项目

时间:2014-01-29 08:36:20

标签: javascript angularjs

下面的代码用于检索每个类别的总数,我有4个。我通过循环计算所有现有类别的长度,然后使用switch来收集所有类别。它有效,我给了我a = 3,b = 2,c = 10和d = 20.

但是当我在插入新值时运行此函数时,它不起作用。例如,插入了新对象,该函数重新计算并给出错误的值。

我写了这个

            $scope.countNote = 0;
            $scope.countQuote = 0;
            $scope.countProject = 0;
            $scope.countSkill = 0;

            $scope.countState = function () {

                for (var i = 0; i < $scope.postItem.length; i++)                             {
                    $loopObj = $scope.postItem[i].category_id;


                    switch ($loopObj) {
                        case '1':
                            $scope.countNote++;
                            break;
                        case '2':
                            $scope.countQuote++;
                            break;
                        case '3':
                            $scope.countProject++;
                            break;
                        case '4':
                            $scope.countSkill++;
                            break;
                    }
                }



            }

1 个答案:

答案 0 :(得分:1)

在函数内部移动初始化程序,并在每次推送后调用它

$scope.countState = function () {
            $scope.countNote = 0;
            $scope.countQuote = 0;
            $scope.countProject = 0;
            $scope.countSkill = 0;
          for (var i = 0; i < $scope.postItem.length; i++)                             {
                    $loopObj = $scope.postItem[i].category_id;
                    switch ($loopObj) {
                        case '1':
                            $scope.countNote++;
                            break;
                        case '2':
                            $scope.countQuote++;
                            break;
                        case '3':
                            $scope.countProject++;
                            break;
                        case '4':
                            $scope.countSkill++;
                            break;
                    }
                }

            }