Angular JS服务无法工作

Angular JS services not working

本文关键字:工作 服务 JS Angular      更新时间:2023-09-26

所以我对angularjs有点陌生,并且在服务方面面临一些困难。所以我正在做一个angularjs TO DO应用程序和服务,不能让它工作。这是我的控制器

.controller("myController", ['$scope','toDoService', function($scope,toDoService){
    var lists = toDoService.getLists();
    $scope.lists = lists;
    $scope.add = function(){
      // WHAT TO PUT HERE????
    }

and this is my service

 .service('toDoService', function(){
      this.getLists =function(){
          var list = [
              {"name" : "abebe" ,"done":false, id: Date.now()}
          ];
          return list;
      }

      this.add = function(){
         $scope.lists.push({'name':$scope.nameSpace,'done':false, id: Date.now()});
      $scope.nameSpace = '';
         return this;
      }
  });

提前致谢

你不能在这样的服务中使用$scope

查看答案:https://stackoverflow.com/a/22899880/3619813

你不能在service中使用$scope。检查Fiddle以了解它应该如何工作。

myApp.service('toDoService', function(){
            this.details = {
        lists: [
              {"name" : "abebe" ,"done":false, id: Date.now()}
          ]
      }
      this.getLists =function(){
          var list = [
              {"name" : "abebe" ,"done":false, id: Date.now()}
          ];
          return list;
      }
      this.addList = function(item) {
        this.details.lists.push(item)
      }
  });
myApp.controller("myController", ['$scope','toDoService',       
    function($scope,toDoService){
    $scope.lists = function() { return toDoService.details.lists };
    $scope.add = function(){
      // WHAT TO PUT HERE????
      var newListItem = {"name" : "abebe" ,"done":false, id: Date.now()}
      toDoService.addList(newListItem)
    }
}]);

下面是完整的代码。

.controller("myController", ['$scope','toDoService', function($scope,toDoService){
var lists = toDoService.getLists();
$scope.lists = lists;
$scope.add = function(){
    toDoService.add($scope.lists);
}

您的服务将如下所示:

.service('toDoService', function(){
    this.lists = [];
    this.getLists =function(){
        var list = [
            {"name" : "abebe" ,"done":false, id: Date.now()}
        ];
        return list;
    }

    this.add = function(data){
        lists.push(data);
        return lists;
    }
});