2016-07-21 2 views
0

私は、ファクトリがデータを取得した後に起こるコントローラの機能の中で配列を宣言しようとしています。そして、関数の完了後にアクセスします。ここでは、私は私のコードのために持っているものだ:私は私のコントローラの終わりに向かってコメントで尋ねてきたようにAngularJS:約束の中から変数にアクセスしてコントローラ内で使用する方法は?

app.controller('SignUpController', function ($scope, $http, $location, DailyCounterService, $localStorage) { 

    DailyCounterService.GetDailyCountersList().then(function (d) { 
     $scope.DailyCounters = d.data; 
     $scope.allCounters = []; 

     var daySixteen = d.data.filter(function (d) { 
      // This is where I'm building the array I want to access later 
      $scope.allCounters.push(d.MICounter); 

      return d.MIDay === "16"; 
     }); 

     console.log($scope.allCounters); 
     // This prints in console '[2, 6, 1, 1, 7, 8, 2......]' 
     // So the array is now initialized 

    }, function (error) { 
     alert('Error!'); 
    }); 

    // Here is where I want to access $scope.allCounters once again 
    // But Can't because doing this: 
    console.log($scope.allCounters); 
    // prints 'undefined' 
    // How would I make $scope.allCounters be able to be accessed here? 
}) 
.factory('DailyCounterService', function ($http) { 
    var fac = {}; 
    fac.GetDailyCountersList = function() { 
     return $http.get('/Data/GetDailyCountersList') 
    } 
    return fac; 
}) 

、どのように私は、その関数の機能以前の外で変数セットにアクセスすることができるだろうか? 、

+0

:決意の

詳細。 – jbrown

+0

@brownは、私の現在の設定で、 '.then()'関数の外側でデータをアクセスできるようにすることができます。どんな種類のローカルストレージの回避策ですか? – NoReceipt4Panda

+0

コントローラーの初期化で$ scope.allCountersを使用することを前提としていますか? – jbrown

答えて

1

さて、このコントローラは、ルートに関連付けられている場合、あなたは、このようなルートプロバイダの解決属性に

.when("/signup", { 
    templateUrl: "signup.html", 
    controller: "SignUpController", 
    resolve: { 
     allCounters: 
     function(DailyCounterService){ 
      DailyCounterService.GetDailyCountersList().then(function (d) { 
      // Do your stuff 
      return allCounters; 
     }, function (error) { 
      alert('Error!'); 
     }); 
     } 
    } 
}), 

をこの取得コードを縛ることができ、あなたの中にアクセスallCountersは次のようにコントローラお使いのコントローラがロードされたときに、すべてのカウンタが常に初期化されます。この方法により、

app.controller('SignUpController', function ($scope, $http, $location, allCounters, DailyCounterService, $localStorage) 

。あなたは、コントローラの初期化で$ scope.allCountersを使用する場合は、それはそれは、初期化時に利用できるようになります唯一の時間であるよう.then()メソッドでそれを使用する必要がありますhttp://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

関連する問題