使用数据库中的数据填充数组 (Angular + PHP/MySQL)

Populate an array with data from database (Angular + PHP/MySQL)

我正在开发一个简单的待办事项应用程序,它使用 Angular 然后 PHP/MySQL 作为后端。

我现在有一个简单的应用程序,我可以在其中添加新的待办事项,并使用简单的 $http post 每天将 "percentage completed" 添加到数据库中。

但是现在我要做的是用数据库中的数据填充 $scope.historicalDailyPercentages 数组。

在脚本开始时,我像这样初始化对象:

$scope.historicalDailyPercentages = []; //TODO, this should be initialised with data from the database.

我知道我需要在其中使用某种 $http get 循环来检查数据并填充对象,但我不太清楚如何开始。

完整的goalzy.js脚本如下,供参考。提前致谢!

angular.module('goalzy', [])

.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.headers.post['Content-Type'] = 'application/json; charset=utf-8';
}])

.controller('TodoController', ['$scope', '$http', function($scope, $http) {

    $scope.todos = [];
    $scope.historicalDailyPercentages = []; //TODO, this should be initialised with data from the database.

    $scope.addTodo = function() {
        if ($scope.todoText != "") {
            if ($scope.todos.length < 3) {
                $scope.todos.push({
                    text: $scope.todoText,
                    done: false
                });
                $scope.todoText = '';
                //Save to DB
            } else {
                alert("You can only have 3 todos per day!");
                $scope.todoText = '';
            }
        } else {
            alert("you must write something");
        }
    };

    $scope.remaining = function() {
        var count = 0;
        angular.forEach($scope.todos, function(todo) {
            count += todo.done ? 0 : 1;
        });
        return count;
    };

    $scope.percentComplete = function() {
        var countCompleted = 0;
        angular.forEach($scope.todos, function(todo) {
            countCompleted += todo.done ? 1 : 0; //Simply calculates how many tasks have been completed
            console.log(countCompleted);
        });
        var totalCount = $scope.todos.length;
        var percentComplete = countCompleted / totalCount * 100;
        return percentComplete;
    }

    $scope.finaliseDay = function(percentComplete) {
        alert("You're finalising this day with a percentage of: " + percentComplete);
        var today = new Date();
        var alreadyPresent = $scope.historicalDailyPercentages.some(function(item) {
            return item.date.getFullYear() === today.getFullYear() &&
                item.date.getMonth() === today.getMonth() &&
                item.date.getDate() === today.getDate();
        });

        //Confirm that nothing has alreayd been posted for today
        if (!alreadyPresent) {

            // Simple POST request example (passing data)
            $http.post('/postDailyPercentage.php', {
                user_id: 1,
                percent: percentComplete,
                date: today
            }).
            success(function(data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
                if (data) {

                    $scope.historicalDailyPercentages.push({
                        user_id: 1,
                        percent: percentComplete,
                        date: today
                    });

                } else {
                    alert("Something went wrong" + data);
                }

            }).
            error(function(data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                console.log("Post failure");
            });
        } else {
            alert("You're all set for today - see you tomorrow!");
        }

        //console.log($scope.historicalDailyPercentages);
    }
}]);

要用 $http.get 填充该对象,您可以按如下方式进行:

function getHistoricalDataSuccess(data) {
  $scope.historicalDailyPercentages = data;
}

function getHistoricalDataError(error) {
  //handle the error
}

$http.get('path/to/api')
.success(getHistoricalDataSuccess)
.error(getHistoricalDataError);
var TodoController = function($scope, HistoricalDailyPercentageService) {
  HistoricalDailyPercentageService.get().then(function(percentages) {
    $scope.historicalDailyPercentages = percentages;
  }, function(error) {
    alert(error);
  });
};

var HistoricalDailyPercentageService = function($http) {
  this.get = function() {
    return $http.get('yourUrl')
      .then(function(xhr) {
        var data = xhr.data;
        // Transform the data as you see fit
        return data;
      }, function(xhr) {
        // xhr contains the error message - modify this as you see fit.
        return xhr.code;
      });
  };
};

angular.module('goalzy')
  .controller('TodoController', ['$scope', 'HistoricalDailyPercentages', TodoController])
  .service('HistoricalDailyPercentageService', ['$http', HistoricalDailyPercentageService]);

我建议这样做;这将使通过从已经很忙的控制器中获取数据的逻辑更容易测试。 @RVandersteen 的例子只能在你的控制器内部工作,这很好,但它确实会让你的控制器非常忙碌;控制器实际上应该只将事物分配给一个范围,其他一切都应该在指令中处理(例如,将事件绑定到方法)或 service/factory/provider(用于业务逻辑)。

完成代码后,你可以在 CodeReview 上 post 吗?我可以建议一些改进,但它们只是基于审查的东西,不适合这个问题的范围。

值得注意的是,因为我在控制器中使用 then,所以我也必须在服务中使用 then。如果我在服务中使用 success,那么当我在控制器中调用 then 时,我的更改将不会反映出来。