Push data from controller to JSON in service

57 Views Asked by At

I am facing a problem in pushing data value to a JSON which is in service. I have less idea of pushing data to service in AngularJS.

Example I have created a function to show year and time in Controller:-

appName.controller('uController', function ($scope,ConsoleService) {
    $scope.showPushData = function(){
            $scope.date = new Date();
             console.log($scope.date);
            $scope.year = $scope.date.getFullYear();
             console.log($scope.year);
            $scope.time =  $scope.date.getTime();
             console.log($scope.time);
            $scope.ConsoleService.consoleList.year.push($scope.year);
    }
})

And in my service I have :-

appName.service('ConsoleService', function ($http) {
this.getInfo = function() {    
var consoleList = [{
    "year" : "",
    "time" :""
    }]
}
})

I want to push $scope.year value from controller to "year" : "" in service. How can I call service to controller fro this ?

2

There are 2 best solutions below

0
On

in the bellow code can stored the array .But display in the html page

appName.controller('uController', function ($scope,ConsoleService) {
    $scope.values = []; 
    $scope.showPushData = function(){
            $scope.date = new Date();
             console.log($scope.date);
            $scope.year = $scope.date.getFullYear();
             console.log($scope.year);
            $scope.time =  $scope.date.getTime();
             console.log($scope.time);
     var value = {"year": $scope.year,"time": $scope.time}; 
           $scope.values =  ConsoleService.getInfo(value);
    }
});

appName.service('ConsoleService', function ($http) {
this.consoleList = [];
this.getInfo = function(values) {    
consoleList.push(values);
return consoleList;
}
});

0
On

I have created something like this and now getting it successfully.

appName.controller('uController', function ($scope, ConsoleService) {
$scope.date = new Date();
  $scope.year = $scope.date.getFullYear();
  $scope.time =  $scope.date.getTime();
  
  $scope.newArr = {
                    "year": $scope.year,
                    "time": $scope.time
                  };
  
  ConsoleService.addItem($scope.newArr);
  $scope.getval = ConsoleService.getList();
})

appName.service('ConsoleService', function ($http) {
   
var consoleList = [];

return {
    addItem: addItem,
    getList: getList,
  };  
    function addItem(item) {
    consoleList.push(item);
  }
  function getList() {
    return consoleList;
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>