【发布时间】:2017-06-25 07:28:49
【问题描述】:
我正在尝试使用 $http.get 方法将待办事项从我的控制器添加到我的数据库。但我收到错误“TypeError:$scope.todos.push 不是函数”。我已经查看了许多与我自己类似的问题,并尝试实施这些建议,但没有成功。问题出在 TodoController 的 $scope.createTodo 函数中。
todo.controller.js
angular.module('app')
.controller('TodoController', ['$scope', 'Todos', function TodoController($scope, Todos) {
$scope.formData = {};
console.log("in the TodoController");
// when landing on the page, get all todos and show them
Todos.get()
.then(function (data){
$scope.todos = data;
}).then(function (error){
});
$scope.createTodo = function() {
if(!$scope.todoForm.$valid) {
return;
}
Todos.create($scope.formData)
.then(function (data){
$scope.formData = {};
$scope.todos.push(data);
}).then(function (error){
});
};
todo.service.js
angular.module('app')
.factory('Todos', ['$http', function($http) {
return {
get: function() {
return $http.get('/api/todos');
},
create: function(todoData) {
return $http.get('/api/todos', todoData).then(function (success){
},function (error){
});
},
delete: function(id) {
return $http.delete('/api/todos/' + id);
},
update: function(todoData) {
return $http.put('/api/todos/' + todoData.id, todoData);
}
}
}]);
【问题讨论】:
-
在
Todos.get().then(function (data){ ... })中放置一个断点,然后检查您分配给$scope.todos的确切内容。我猜它不是一个数组。 -
问题是您对
todos的初始分配-您应该在.then响应中记录data变量-它不是数组
标签: javascript angularjs http typeerror