[英]AngularJs - Code accessing $scope variable before it is ready
我有一個控制器(MyCtrl)。 首先要做的是撥打http.get
並獲取響應並將其分配給$scope.input
。 控制器的其余部分取決於$scope.input
。 但是問題是控制器中的代碼嘗試在http調用完成之前訪問$scope.input
。
我該如何解決?
app.controller('MyCtrl', function($scope, $http, $routeParams, factory) {
factory.getInfo($routeParams.id)
.success(function(response) {
//The factory code make the http.get call
$scope.input = response;
});
//Rest of code accessing $scope.input before it is ready
});
PS:我不想將rest of controller code
放在success
塊內
謝謝
選項1:使用一些初始化功能
您可以將初始化邏輯移至名為initialize()
的函數,然后在AJAX調用的成功回調中調用該函數。
app.controller('MyCtrl', function($scope, $http, $routeParams, factory) {
factory.getInfo($routeParams.id)
.success(function(response) {
initialize(response);
});
function initialize(){
/* Move only the logic that depends on response from AJAX call in to
this method.
All utility functions, event handlers on scope are still outside
this function
*/
$scope.input = response;
}
});
選項2:使用解決方法
您還可以使用resolve
功能在初始化控制器之前加載所有依賴項,如下所示。
在您的路由器配置中
$routeProvider
.when('/home/:id', {
templateUrl: 'home.html',
controller: 'MyCtrl',
resolve: {
factory : 'factory',
initData: function(factory,$route){
return factory.getInfo($route.current.params.id);
}
}
});
在您的控制器中
app.controller('MyCtrl', function($scope, $http, initData){
$scope.input = initData;
// rest of your logic
});
有關此控制器激活和路由解析模式的更多信息,可以參考this和this 。
希望這可以幫助 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.