AngularJS是否等待数据渲染视图?

AngularJS是否等待数据渲染视图?,angularjs,Angularjs,我正在研究angularJS,但我还是初学者。。。我有一个简单的问题,希望你能回答 我得到了以下路由: app.config(function($routeProvider) { $routeProvider .when('/', { controller:'ListCtrl', templateUrl:'list.html' }) .when('/update/:itemId', { controller:'UpdateCtrl', templa

我正在研究angularJS,但我还是初学者。。。我有一个简单的问题,希望你能回答

我得到了以下路由:

app.config(function($routeProvider) {
  $routeProvider
  .when('/', {
    controller:'ListCtrl',
    templateUrl:'list.html'
  })
  .when('/update/:itemId', {
    controller:'UpdateCtrl',
    templateUrl:'update.html'
  })
  [...]
  .otherwise({
    redirectTo:'/'
  });
});
使用location.path从“列表”视图重新生成根目录到“更新”视图:

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调用完成后,将更新范围并填充视图

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


这样做的目的是避免视图为空的短时间。。。(并非真正的用户友好)

您需要使用
$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;
  ...
});
在数据到达(promise已解决)之前,不会更改视图。

请参阅“解决:”