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

时间:2015-03-07 14:05:35

标签: angularjs angular-http

我有一个简单易用的应用程序,我正在使用Angular,然后使用PHP / MySQL作为后端。

我现在有一个简单的应用程序,我可以添加新的待办事项,并添加"已完成的百分比"每天使用简单的$http post访问数据库。

但是,我现在要做的是,使用数据库中的数据填充$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);
    }
}]);

2 个答案:

答案 0 :(得分:1)

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

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

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

$http.get('path/to/api')
.success(getHistoricalDataSuccess)
.error(getHistoricalDataError);

答案 1 :(得分:1)

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的例子只能在您的控制器内部工作,这很好,但它确实让您的控制器非常繁忙;控制器应该只将事物分配给作用域,其他所有内容都应该在指令中处理(例如,将事件绑定到方法)或服务/工厂/提供者(用于业务逻辑)。

完成代码后,您可以在CodeReview上发帖吗?我可以提出一些改进,但它们只是基于评论的事情,不适合这个问题的范围。

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