1

1 つのモジュールが 2 番目のモジュールに依存するアプリを開発しようとしています。最初のモジュール実行関数では、http を使用してサーバーからのデータで templatecache を埋めようとしていますが、http 呼び出しは非同期であるため、最初のモジュールが完了する前に 2 番目のモジュールが実行され、結果が未定義になります。以下のコードは状況をより明確にします

   var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
              $timeout(function () {
                  $templateCache.put('ajay', 'ajay');
              }, 1000);
          }
          ]);

          var secondapp = angular.module('plunker', ['main']);
          secondapp.controller('test', function ($scope, $templateCache, $timeout) {
              // get me undefined i want to wait until module main is finished running run function 
              alert($templateCache.get('ajay'));
          });
4

1 に答える 1

1

非同期性を受け入れる:

 var app = angular.module('main', []).run(["$templateCache",'$http','$timeout', function ($templateCache,$http,$timeout) {
     $templateCache.put('ajay', $http.get("/data/ajay"));
 }
 ]);

 var secondapp = angular.module('plunker', ['main']);
 secondapp.controller('test', function ($scope, $templateCache, $timeout) {
     $templateCache.get('ajay').then(function (data) {
         alert(data);
     });
 });
于 2013-07-03T20:26:20.537 に答える