angularjs在应用程序加载时调用控制器函数

时间:2015-12-11 10:34:03

标签: angularjs

我在控制器中有$ promise服务,我想在应用程序启动时调用这些服务。

 CustomerService.fetchReligion.list().$promise.then(function(response){
      $scope.religionList = response; 
      $window.localStorage.setItem('religionList', JSON.stringify(response));                                                      
   }, function(error) {
      // error handler
  });     
  CustomerService.fetchCaste.list().$promise.then(function(response){
    $scope.casteList = response;  
    $window.localStorage.setItem('casteList', JSON.stringify(response));                                                                               
    }, function(error) {
     // error handler
  });

我如何称呼这些服务?

1 个答案:

答案 0 :(得分:0)

执行此操作的一种方法是使用UI-Router。 UI-Router有一个"Resolve" functionality,其中,只要视图变为特定状态,就应该解析promises并在实例化相应的控制器之前将其作为一个值。这意味着无论何时加载新的状态/视图(及其控制器),都可以确保已经检索到所需的对象/值并准备好使用。

以下代码段直接取自UI-Router的文档。

$stateProvider.state('myState', {
  resolve:{

     ...

     // Example using function with returned promise.
     // This is the typical use case of resolve.
     // You need to inject any services that you are
     // using, e.g. $http in this example
     promiseObj:  function($http){
        // $http returns a promise for the url data
        return $http({method: 'GET', url: '/someUrl'});
     },

     // Another promise example. If you need to do some 
     // processing of the result, use .then, and your 
     // promise is chained in for free. This is another
     // typical use case of resolve.
     promiseObj2:  function($http){
        return $http({method: 'GET', url: '/someUrl'})
           .then (function (data) {
               return doSomeStuffFirst(data);
           });
     },        

     ...

  // The controller waits for every one of the above items to be
  // completely resolved before instantiation. For example, the
  // controller will not instantiate until promiseObj's promise has 
  // been resolved. Then those objects are injected into the controller
  // and available for use.  
  controller: function($scope, simpleObj, promiseObj, promiseObj2, translations, translations2, greeting){

      ...

      // You can be sure that promiseObj is ready to use!
      $scope.items = promiseObj.data.items;
      $scope.items = promiseObj2.items;

      ...
  }
})