如何在angularjs中交叉模块之间共享数据?

时间:2015-03-16 04:44:53

标签: javascript angularjs html5

我在同一页面中有两个名为" uploadModule" " graphModule" 的模块 uploadModule 浏览数据并将其保存在服务(sharedDataObject)上,我想将此数据量共享到另一个模块(graphModule)



var uploadModule = angular.module('uploadModule', ['ngRoute']);
uploadModule.config(function ($routeProvider) {
    $routeProvider
            .when('/',
                    {
                        controller: 'dataSetController',
                        templateUrl: 'view1.html'
                    })
            .when('/view2',
                    {
                        controller: 'compineGraphsWithData',
                        templateUrl: 'view2.html'
                    })
            .otherwise({redirectTo: '/'})
});

uploadModule.service('sharedDataObject', function () {
 
        this.getDataObject= function () {
            return this.dataObject;
        };
        this.setDataObject= function (value) {
            this.dataObject = value;
        };
   
});//this service to share Data Object between controlles(graphs)

uploadModule.controller('dataSetController', dataSetController);//load data set and but it on sharedDataObject service
function dataSetController($scope, sharedDataObject) {
    $scope.datasetfile;
    var file;
    $scope.getDataSetFile = function (files) {
        file = files[0];
        $scope.datasetfile = file.name;

        var reader = new FileReader();
        reader.onload = function (evt) {
            var result = evt.target.result;
            var Json;
            Json = CSV2JSON(result);
            dataset = JSON.parse(Json);
            sharedDataObject.setDataObject(dataset);
            console.log(dataset);
              
        };
        reader.readAsText(file);
        $scope.$apply();
    };
}
;

var graphModule = angular.module("graphModule", ['uploadModule']);
            graphModule.controller('createGraph', createGraph);
            function createGraph($scope ,sharedDataObject ) {
                $scope.Scatter = function () {
                    console.log(sharedDataObject.getDataobject());
                };
            }
            ;//compineGraphsWithData and fire graph function
 angular.bootstrap(document.getElementById("App2"),['graphModule']);

<input type="file"  id="dataset" name='file' onchange="angular.element(this).scope().getDataSetFile(this.files)" />
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

函数名称似乎不正确:

console.log(sharedDataObject.getDataobject());

应该是:

console.log(sharedDataObject.getDataObject());

修改: 我不知道,一切似乎都很好。 Angularjs服务可用于在控制器之间共享数据,即使它们属于不同的模块。 由于我不知道你是完整的脚本,我根据你的示例代码编写了一个示例。这是它:

    <html><head>
    <style>        
    </style>    
</head>
<body>
<div ng-app="graphModule">
    <div ng-controller="dataSetController">
    <input type="file" id="dataset" name="file" onchange="angular.element(this).scope().getDataSetFile(this.files)">    
    </div>  
    <div ng-controller="createGraph">
    <button ng-click="Scatter()">Click me</button>
    </div>
</div>


    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <script>

var uploadModule = angular.module('uploadModule', []);

uploadModule.service('sharedDataObject', function () {

  this.getDataObject = function () {
    return this.dataObject;
  };
  this.setDataObject = function (value) {
    this.dataObject = value;
  };

});//this service to share Data Object between controlles(graphs)

uploadModule.controller('dataSetController', dataSetController);//load data set and but it on sharedDataObject service
function dataSetController($scope, sharedDataObject) {
  $scope.datasetfile;
  var file;
  $scope.getDataSetFile = function (files) {
    file = files[0];
    $scope.datasetfile = file.name;

    var reader = new FileReader();
    reader.onload = function (evt) {
      var result = evt.target.result;
      var Json;
      //Json = CSV2JSON(result);
      Json = result;
      //dataset = JSON.parse(Json);
      dataset = Json;
      sharedDataObject.setDataObject(dataset);
      console.log(dataset);

    };
    reader.readAsText(file);
    $scope.$apply();
  };
}
;

var graphModule = angular.module("graphModule", ['uploadModule']);
graphModule.controller('createGraph', createGraph);
function createGraph($scope, sharedDataObject) {
  $scope.Scatter = function () {
    console.log(sharedDataObject.getDataObject());
  };
}

;//compineGraphsWithData and fire graph function
// angular.bootstrap(document.getElementById("App2"),['graphModule']);

    </script>
</body></html>

答案 1 :(得分:1)

使用服务在控制器之间共享数据的方法遵循以下模式: http://embed.plnkr.co/ohkXfy/preview

var myApp = angular.module('myApp', []);
myApp.service('sharedModels', [function () {
    'use strict';

    // Shared Models
    this.data = {breakfast: 'eggs'};

}]);

myApp.controller('Ctrl1', ['$scope', 'sharedModels', function($scope, sharedModels) {

    $scope.myBreakfast = sharedModels.data;
}]);

myApp.controller('Ctrl2', ['$scope', 'sharedModels', function($scope, sharedModels) {

    $scope.yourBreakfast = sharedModels.data
}]);

myApp.controller('Ctrl3', ['$scope', 'sharedModels', function($scope, sharedModels) {

    $scope.ourBreakfast = sharedModels.data;
}]);`

答案 2 :(得分:1)

您应该将公共状态提取到其自己的模块中,并将其作为依赖项添加到两个模块中。然后,您可以在两个模块中访问相同的共享状态。

编辑:我在Plunker中举例说明了我的意思。

因此,您创建一个包含两个模块所需服务的模块:

(function(){
  angular.module("sharedData", [])
    .service("sharedService", function(){
      this.getSharedData = function(){
        return this.sharedObject;
      };

      this.setSharedData = function(newData){
        this.sharedObject = newData;
      };
    });
}());

然后,您将此模块作为需要它的模块的依赖项:

(function(){
  angular.module("firstModule", ["sharedData"])
    .controller("firstCtrl", function($scope, sharedService){
      $scope.get = function(){
        $scope.data = sharedService.getSharedData();
      };
    });
}());
(function(){
  angular.module("secondModule", ["sharedData"])
    .controller("secondCtrl", function($scope, sharedService){
      $scope.set = function(){
        sharedService.setSharedData("Test");
      };
    });
}());

如果您有更多问题,请提前询问。