1

我试图把头绕在ui-router上,并尝试实现以下逻辑:

  • 如果没有状态,请转到状态/项目
  • 处理时/items,从服务器检索“项目”列表
  • 当收到“item”时进入 state /items/:item,其中“item”是项目列表中的第一个,由服务器返回
  • 在状态/items/:item渲染一个项目列表,相应的“项目”被“突出显示”(突出显示部分不包含在我的代码中)

但是,子状态的“控制器”功能并未执行。我敢打赌,这真的很明显。

这是 js(我在 plunkr 上也有它以及随附的模板)。

angular.module('uiproblem', ['ui.router'])
.config(['$stateProvider', '$urlRouterProvider',
         function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/items');
    $stateProvider
    .state('items', {
        url: '/items',
        resolve: {
            items: function($q, $timeout){
              var deferred = $q.defer();
              $timeout(function() {
                deferred.resolve([5, 3, 6]);
              }, 1000);
              return deferred.promise;
            }
        },
        controller: function($state, items) {
            // We get to this point successfully
            console.log(items);
            if (items.length) {
                // Attempt to transfer to child state
                return $state.go('items.current', {id: items[0]});
            }
        }
    })
    .state('items.current', {
        url: '/:id',
        templateUrl: 'item.html',
        controller: function($scope, items) {
            // This is never reached, but the I can see the partial being
            // loaded.
            console.log(items);
            // I expect "items" to reflect to value, to which the "items"
            // promise resolved during processing of parent state.
            $scope.items = items;
        }
    });
}]);

Plunk:http ://plnkr.co/edit/K2uiRKFqe2u5kbtTKTOH

4

1 回答 1

5

Add this to your items state:

template: "<ui-view></ui-view>",

States in UI-Router are hierarchical, and so are their views. As items.current is a child of items, so is it's template. Therefore, the child template expects to have a parent ui-view to load into.

If you prefer to have the child view replace the parent view, change the config for items.current to the following:

{
  url: '/:id',
  views: {
    "@": {
      templateUrl: 'item.html',
      controller: function($scope, items) {
          // ...
      }
    }
  }
}
于 2013-09-20T22:12:15.927 回答