删除服务中的Todo数据,而不是使用控制器中的范围

时间:2015-12-27 08:14:58

标签: angularjs

这是我的代码

angular.module("todoListApp", [])
.controller('mainCtrl',  function($scope, dataService){

/* updated */
 dataService.getTodos(function(response){
  console.log(response.data);
  $scope.todos = response.data;

 })

 $scope.deleteTodo = function(todo, $index){
 dataService.deleteTodo(todo, $index);
  $scope.todos.splice($index, 1);
}


})
.service('dataService', function($http){
 /* Updated */
this.getTodos = function(callback){
$http.get('../mock/todos.json').then(callback);
};
this.deleteTodo = function(todo, $index){
console.log("The todo" + todo.name + " todo has been deleted ");

};

我想在服务的deleteTodo方法中实现deleteTodo方法,而不是在控制器中使用$scope.todos.splice

任何替代方法都可以做到这一点?

更新

我更新了获取数据的代码。希望有助于更好地回答。

2 个答案:

答案 0 :(得分:0)

您应该在服务中执行所有数组操作:

angular.module("todoListApp", [])
.controller('mainCtrl',  function($scope, dataService){

   $scope.deleteTodo = function(todo, $index){
     dataService.deleteTodo(todo, $index);
   }
})
.service('dataService', function($http){
self = this;
this.todos = [];

this.addTodo = function(todo){
  self.todos.push(todo)
  //more stuff
}

this.deleteTodo = function(todo, $index){
  self.todos.splice($index, 1);
  console.log("The todo" + todo.name + " todo has been deleted ");
};

如果要将待办事项绑定到视图中的某个列表,则应直接绑定到服务对象:

$scope.todos = dataService.todos;

答案 1 :(得分:0)

执行此操作的一种方法是让服务返回$ http承诺(假设您使用$ http在todos列表上执行添加/编辑/删除操作) 这样的事情(未经测试):

angular.module("todoListApp", [])
  .controller('mainCtrl',  function($scope, dataService) {
    $scope.deleteTodo = function(todo, $index) {
      dataService.deleteTodo(todo, $index).success(function(data) {
        $scope.todos = data;
      });
    };
  })
  .service('dataService', function($http) {
    this.deleteTodo = function(todo, $index){
      console.log("The todo" + todo.name + " todo has been deleted ");
      var url = '/todos/' + id; //whatever the url to your delete todo api is
      return $http.delete(url);
    };
  });