2016-08-10 81 views
1

所以我有點新的angularjs和麪臨一些服務的困難。所以我正在研究一個angularjs TO DO應用程序和服務,並且無法正常工作。 這是我的控制器角JS服務不起作用

.controller("myController", ['$scope','toDoService', function($scope,toDoService){ 

    var lists = toDoService.getLists(); 
    $scope.lists = lists; 

    $scope.add = function(){ 
     // WHAT TO PUT HERE???? 

    } 

,這是我的服務

.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; 
     } 

    }); 

預先感謝您

+0

你有什麼錯誤嗎? – DMCISSOKHO

+0

nop,我的控制檯沒有錯誤 – Harun

回答

1

不能使用內部服務$範圍。檢查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) 
    } 
}]); 
0

以下是完整的代碼。

.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; 
    } 

});