在服务中将数据从控制器推送到JSON

时间:2018-10-05 13:20:26

标签: angularjs json angular-services angular-controller

我在将数据值推送到正在使用的JSON时遇到问题。我不太想在AngularJS中将数据推送到服务。

示例我创建了一个在 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);
    }
})

在我的服务中,我有:-

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

我想在服务中将$scope.year值从控制器推送到"year" : ""。我如何才能为此打电话给控制器服务?

2 个答案:

答案 0 :(得分:0)

在下面的代码中

可以存储数组。但是在html页面中显示

List<AnyType> numbers = new ArrayList<AnyType>((Collection<? extends AnyType>)
        Arrays.asList(5, 20, 25, 50, 66, 75, 80, 90, 92, 95, 111, 150, 166, 175, 200));

答案 1 :(得分:0)

我已经创建了类似的东西,现在成功了。

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>