2014-01-30 42 views
1

我正在研究angularJS,但我仍然是初学者...而我有一个简单的问题,我希望你能回答。使用location.pathAngularJS等待数据呈现视图?

app.config(function($routeProvider) { 
    $routeProvider 
    .when('/', { 
    controller:'ListCtrl', 
    templateUrl:'list.html' 
    }) 
    .when('/update/:itemId', { 
    controller:'UpdateCtrl', 
    templateUrl:'update.html' 
    }) 
    [...] 
    .otherwise({ 
    redirectTo:'/' 
    }); 
}); 

从“名单”的观点,我重新根“更新”的观点:

app.controller('ListCtrl', function($scope, albumFactory, $location, $http) { 
    $scope.albums = albumFactory.getList().then(function(albums){ 
     $scope.albums = albums; 
    }); 
    [...] 
    $scope.updateAlbum = function(index) { 
     console.log('updateAlbum()'); 
     $location.path("/update/" + $scope.albums.albums[index].id); 
    } 

在更新

我得到了以下路由控制器我需要首先检索细节以预先填充视图。为此,我使用的工厂如下:

app.controller('UpdateCtrl', function($scope, albumFactory, $location, $routeParams, $http) { 

    $scope.album = albumFactory.get($routeParams.itemId).then(function(album){ 
     $scope.album = album; 
    }); 

所以我的问题是视图首先呈现(显示)为空。一旦来自工厂的Ajax调用完成,作用域就会更新并且视图被填充。

是否可以在渲染局部视图之前等待工厂回复? 或者我做错了什么?

的目的是为了避免在很短的时间,其中的观点是空的......(不是真正用户友好的)

+3

请参阅'resolve:'[docs](http://docs.angularjs.org/api/ngRoute.$routeProvider) – calebboyd

回答

2

您需要使用$route缓解。

app.config(function($routeProvider) { 
    $routeProvider 
    .when('/', { 
    controller:'ListCtrl', 
    templateUrl:'list.html' 
    resolve : { 
     resolvedAlbums: function(albumFactory) { 
     return albumFactory.getList(); 
     } 
    } 
    }), 
    .when('/update/:itemId', { 
    controller:'UpdateCtrl', 
    templateUrl:'update.html', 
    resolve : { 
     // you can inject services in resolves, in this case you also need `$route` 
     // to get the `itemId` 
     resolvedAlbum: function(albumFactory, $route) { 
     return albumFactory.get($route.current.params.itemId); 
     } 
    } 
    }) 
}); 

您可以再注入所解析数据这样的控制器内部:

app.controller('ListCtrl', function($scope, resolvedAlbums) { 
    $scope.albums = resolvedAlbums; 
    ... 
}); 

app.controller('UpdateCtrl', function($scope, resolvedAlbum) { 
    $scope.album = resolvedAlbum; 
    ... 
}); 

的观点不会改变,直到数据到达后(承诺解决)。

+0

是的!它非常感谢! –