2014-09-29 29 views
0

我想知道最好的時刻是什麼,而初始化應用程序來檢索數據: 1 - REST服務 2 - $ routeParams 定義應用程序範圍不變。REST調用

config階段只接受提供程序,在config/run階段期間$ routeParams屬性未定義。

這個有點好像在正確的方向: Can you pass parameters to an AngularJS controller on creation?

另外:如何在控制器內定義常量,這可能嗎?

app.controller('MainCtrl', function($scope) { 
    //define app.constant here 
} 

--edit:錯字

+0

運行的控制器之前的配置後運行。運行塊 - 在創建注入器後執行並用於啓動應用程序。 – 2014-09-29 13:47:35

回答

1

在運行階段所有的供應商應初始化並工作正常,你可以使用$ HTTP服務檢索以往任何時候都需要什麼樣的參數爲您服務。

我很確定$ routeParams在運行階段也被初始化。在我看來,在控制器中定義常量並不是一個好的做法,如果它們對於那個控制器是唯一的,那麼它們只是變量,如果你想要真正的應用程序範圍的常量,那麼使用一個服務,這就是他們所需要的針對:)

我知道一個簡單的方法來傳遞參數給上創建控制器,它是使用角度UI路由器項目:https://github.com/angular-ui/ui-router

在解析功能,你可以做HTTP調用如果需要的話,注入的常數等等,它非常方便,我個人從來沒有建立一個有角度的項目。

我很確定有更多的方法,但通常在控制器之間傳遞數據的最佳做法是使用服務。

請注意,如果您有一個數據對於多個控制器是通用的,那麼最簡單的方法是將該數據放在服務上並對該服務返回值進行監視,例如說我有isLoggedIn,它可以在任何時刻改變和大量的控制器將要被通知它,使用UserService並觀看它的價值:

UserService.isLoggedIn = function() { 
    return _isLoggedIn; 
} 

而在你的控制器:

我希望這有助於!

1

http://www.jvandemo.com/how-to-resolve-angularjs-resources-with-ui-router/似乎是一個很好的指南,基本上,你的決心添加到狀態:

.state("customers", { 
     url : "/customers", 
     templateUrl: 'customers.html', 
     resolve: { 
      //any value you want, this function should return a promise, 
      //only when that promise is resolved, it will instantiate the controller 
      //Make sure however you add some signal that something is happening because 
      //while fetching it can seem like the page is not responding 
      customers: ['$http', 'anyOtherServiceYouMightNeed', function($http, otherService){ 
       //return a promise 
       return $http.get('api/customers'); 
      }], 
      //and for constant 
      constants: ['ConfigService', function(config) { 
       return config.appConstants; 
      }] 
     }, 
     //customersCtrl will have customers resolved already 
     controller : 'customersCtrl' 
     }); 

     app.controller('customersCtrl', ['$scope', 'customers', 'constants', 
      function($scope, customers, consts) { 
      //customers will be ready and resolved when the controller is instantiated 
      //you can do this with anything you might need inside a controller 
     }