1

我试图在应用程序启动时加载 JSON,并在我的所有控制器之间传播数据。我知道这不是很难做到,但是我对我读过的所有文章/答案感到困惑,因为它们使用的语法与我不同,有人可以指导我如何做到这一点吗?

我目前正在制作控制器制作 $http.get :

myApp = angular.module("myApp", [])

myApp.controller "HomeCtrl", ($scope, $http, $routeParams) ->
 $http.get('gethome.php').success (data) ->
  $scope.home = data

但是我必须在我想要访问该数据的每个控制器中重复自己

4

2 回答 2

5

I will recommend you using Memoization pattern along with service and reuse the service in the controller

Pls check the below sample code

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

          app.service('cache', function ($http,$q) {
              var mycache={};
              return {
                  getdata: function (key) {
                      var deferred = $q.defer();
                      if (mycache[key]) {
                          deferred.resolve(mycache[key]);
                      }
                      else {
                          $http.get('TextFile.txt').then(function (data) {
                              mycache[key] = data.data;
                              deferred.resolve(mycache[key]);
                          });
                      }
                      return deferred.promise;
                  }
              }
          });


          app.controller('test', function ($scope, cache) {
              cache.getdata('cache').then(function (data) {
                  $scope.data = data;
              });
         });

           app.controller('test1', function ($scope, cache) {
              //since data is already cached now it will server the cached data
              cache.getdata('cache').then(function (data) {
                  $scope.data = data;
              });
         });
于 2013-07-04T14:37:09.183 回答
1

You can access to $scope with :

angular.element(document.getElementById('YourCtrl')).scope();

After, you can init data in all your controllers.

于 2013-07-04T14:21:04.100 回答