1

so i am kinda new to angularjs and is facing a little difficulty with services. so i was working on an angularjs TO DO app and with services and can not get it working. This is my controller

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

  });

THANK YOU IN ADVANCE

2
  • do you have any error ? Commented Aug 10, 2016 at 8:08
  • nop, there are no errors in my console Commented Aug 10, 2016 at 8:10

3 Answers 3

2

You can't use $scope inside a service like this.

See this answer: https://stackoverflow.com/a/22899880/3619813

Sign up to request clarification or add additional context in comments.

Comments

1

You can not use $scope inside service. Check the Fiddle to understand how it should work.

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)
    }
}]);

Comments

0

Below is the complete code.

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

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

$scope.add = function(){
    toDoService.add($scope.lists);

}

Your service will look like below.

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

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.