1
所以,我做了一个待办事项列表使用angularjs
,并作出api
使用php slim framework
和mysql
任务存储。 我试图使用$http
服务来保存/删除/更新数据库中的任务,到目前为止,我想出了这个(代码如下),但由于我不是这方面的专家,所以可能有很多关键错误。
请记住,有关待办事项列表的代码正常工作,我希望为$http
请求提供一些指导和提示。
JS:
var app = angular.module('todoApp', []);
app.controller('TodoListController', ['$scope', '$http', function ($scope, $http) {
$scope.todos = [];
$scope.newField = [];
$scope.customStyle = {};
$scope.date = new Date();
$http({
method: 'POST',
url: 'http://taskapi.dev/api/tasks/add' }).then(function successCallback (response) {
$scope.addTodo = function() {
$scope.todos.push({text: $scope.todoText, done: false, editing: false, date: new Date()});
$scope.todoText = '';
};
$scope.save = function (index) {
$scope.todos[index].editing = false;
$scope.todos[index].createdOn = new Date().getTime();
};
});
$http({
method: 'PUT',
url: 'http://taskapi.dev/api/tasks/update' }).then(function successCallback (response) {
$scope.editTodo = function (todo) {
todo.editing = true;
};
$scope.change = function (field) {
var todoIndex = $scope.todos.indexOf(field);
$scope.newField[todoIndex] = angular.copy(field);
$scope.todos[todoIndex].editing = true;
$scope.todos[todoIndex].LastModifyOn = new Date().getTime();
};
$scope.turnGreen = function (todo) {
todo.customStyle = {'background': 'green'};
};
$scope.turnYellow = function (todo) {
todo.customStyle = {'background': 'yellow'};
};
$scope.turnRed = function (todo) {
todo.customStyle = {'background': 'red'};
};
$scope.cancel = function (index) {
$scope.todos[index] = $scope.newField[index];
};
});
$http({
method: 'DELETE',
url: 'http://taskapi.dev/api/tasks/delete' }).then(function successCallback (response) {
$scope.delete = function() {
var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function (todo) {
if (!todo.done) $scope.todos.push(todo);
});
};
$scope.remove = function() {
$scope.todos.splice(this.$index, 1);
};
});
}]);
画外,我认为如果您从工厂/服务发送请求会更好。这个请求我可以提供给你的另一个提示是使用'$ http.post()',除了'$ http({method:'POST'})' –
首先,正如其他人所说的,你应该避免依赖控制器中的$ http服务。将这些依赖关系封装到数据检索服务中,并在您的控制器中使用这些方法。 – 10BitDev
其次,您将方法添加到$ scope服务到处。由于这些实质上就是您的控制器的“API”,我强烈建议将它们全部定义在文件顶部的单行赋值语句中,以便一目了然地了解您的控制器实际执行的操作。 – 10BitDev