AngularJS - 从json共享控制器之间的数据

时间:2015-03-06 11:13:00

标签: json angularjs controller sharing angular-services

实际上,自从几天以来我遇到了以下问题。我喜欢创建一个从json文件加载数据的小应用程序。该应用程序应包含3个视图!

  • 显示数据列表
  • 编辑视图以更改当前数据
  • 添加视图以存储新数据

现在我学会了使用为每个视图为每个控制器提供数据的服务。

但是当时我的服务只适用于变量内的生成数据。

我如何更改此服务,我的服务将提供.json文件中的数据,该文件可以使用任何控制器进行编辑和更新!

谢谢

这是我的代码和plnker

<!doctype html>
<html ng-app="project">
<head>
    <title>Angular: Service example</title>
    <script src="http://code.angularjs.org/angular-1.0.1.js"></script>
    <script>
var projectModule = angular.module('project',[]);


projectModule.factory('theService', function() {

    return {
        thing : [{"DATE" : "2014","IATA":"DUS","DUTY":"10:12"},
                {"DATE" : "2015","IATA":"MIA","DUTY":"10:12"},
                {"DATE" : "2017","IATA":"JFK","DUTY":"10:12"}]
    };

      /*

  return {
      thing:[function($http) {
        return $http.get('data.json').then(function(response) {})
        return response.data;
      }]
    };

    */

});

function FirstCtrl($scope, theService) {
    $scope.thing = theService.thing;
    $scope.name = "First Controller";
}

function SecondCtrl($scope, theService) {   
    $scope.someThing = theService.thing; 
    $scope.name = "Second Controller!";
}

    </script>
</head>
<body>  
    <div ng-controller="FirstCtrl">
        <h2>{{name}}</h2>
        <div ng-repeat="show in thing">
        <p>
        <b>DATE </b>{{show.DATE}}
        <b>IATA </b>{{show.IATA}}
        <b>DUTY </b>{{show.DUTY}}
      </p>
    </div>

    <div ng-controller="SecondCtrl">
        <h2>{{name}}</h2>

        <div ng-repeat="edit in someThing">
        <p>
        <input ng-model="edit.DATE"/>
        <input ng-model="edit.IATA"/>
        <input ng-model="edit.DUTY"/>
        </p>
        </div>

    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您所要做的就是使用$ http服务并将其返回:

getJson: function() {
   return $http.get('data.json')
}

然后在您的控制器中使用它:

service.getJson(function(data) {
  $scope.thing = data;
})

要将对象转换为json,您需要使用angular.fromJson i angular.toJson

Angular Docs

之后你会这样做:

$http.post('yourjson); 

替换当前的json(保存更改)。

您还应该使用$ http.get重新下载它(以使所有内容同步),如上所述。

我找到了一个例子example。我希望它有所帮助。