AngularJS控制器在范围内包装时不显示数据

时间:2018-07-25 19:00:06

标签: javascript angularjs angularjs-controller

我正在使用AngularJS,在控制器中设置函数时遇到问题。

控制器中的代码

$scope.totalUnpaid = 0;
$scope.totalPaid = 0;
$scope.totalHalfDue = 0;
$scope.totalHourDue = 0;
$scope.totalBuisness = 0;
$scope.totalUnpaidSesh = [];
$scope.totalPaidSesh = [];

const getTheSessions = () => {
  adminService.getAllSessions().then((response) => {
    console.log(response);
    response.data.forEach(e => e.next_class = e.next_class.substring(0, 10));
    $scope.allSessions = response.data;

    for (var payment in $scope.allSessions) { // iterate through all payments
      if ($scope.allSessions[payment].payment == 'Paid') { // if the person has paid
        $scope.totalPaid++; // count a payment
        $scope.totalPaidSesh.push($scope.trainerSesh[payment]);
      } else { // if the person hasn't paid
        $scope.totalUnpaid++; // count a non-payment
        $scope.totalUnpaidSesh.push($scope.allSessions[payment]);
      }
    }

    for (var next_session in $scope.totalUnpaidSesh) {
      if ($scope.totalUnpaidSesh[next_session].next_session == '30_Minute') {
        $scope.totalHalfDue = $scope.totalHalfDue + 25;
      } else if ($scope.unpaidSesh[next_session].next_session == 'Hour_Session') {
        $scope.totalHourDue = $scope.totalHourDue + 50;
      }
    }

    $scope.totalBuisness = $scope.totalHalfDue + $scope.totalHourDue;

  });
};

由于某种原因,我无法获取要显示的数据。如果我通过控制台登录该服务,则可以看到应该显示的数据,但该数据会在控制器中消失。

但是,当我摆脱范围并直接使用这种服务时

  $scope.totalUnpaid = 0;
  $scope.totalPaid = 0;
  $scope.totalHalfDue = 0;
  $scope.totalHourDue = 0;
  $scope.totalBuisness = 0;
  $scope.totalUnpaidSesh = [];
  $scope.totalPaidSesh = [];


  adminService.getAllSessions().then((response) => {

        console.log(response);
        response.data.forEach(e => e.next_class = e.next_class.substring(0, 10));
        $scope.allSessions = response.data;

        for (var payment in $scope.allSessions) { // iterate through all payments
          if ($scope.allSessions[payment].payment == 'Paid') { // if the person has paid
            $scope.totalPaid++; // count a payment
            $scope.totalPaidSesh.push($scope.trainerSesh[payment]);
          } else { // if the person hasn't paid
            $scope.totalUnpaid++; // count a non-payment
            $scope.totalUnpaidSesh.push($scope.allSessions[payment]);
          }
        }

        for (var next_session in $scope.totalUnpaidSesh) {
          if ($scope.totalUnpaidSesh[next_session].next_session == '30_Minute') {
            $scope.totalHalfDue = $scope.totalHalfDue + 25;
          } else if ($scope.unpaidSesh[next_session].next_session == 'Hour_Session') {
            $scope.totalHourDue = $scope.totalHourDue + 50;
          }
        }

        $scope.totalBuisness = $scope.totalHalfDue + $scope.totalHourDue;

  });

我得到了数据。

为什么这样做有效,但是当我附加方法

const getTheSessions = () => {

不是吗?

1 个答案:

答案 0 :(得分:0)

使用!!生命周期挂钩:

$ngInit