在Ui-Router中将已解析的数据传递给子状态

时间:2017-07-27 13:23:49

标签: angularjs angular-ui-router

所以,我有一个状态,分辨率吐出一个在前端正确显示的数组。

但我似乎无法将父解析数据传递给子状态。

$stateProvider.state('berliner', {
  url: '/berlinerliste',
  params : {search: 'Berliner 2017'},
  resolve: {
    fair: function(SearchService, $stateParams) {
      return SearchService.getAllExhibitors($stateParams.search);
    }
  },
  views: {
    'header': {   
      templateUrl: 'header.htm'   
    },
    'main':{    
      templateUrl: 'bl2017.htm',
      controller: function($scope, fair){
        $scope.fair = fair;
        console.log($scope.fair);
      }    
    }
  }
})

.state('berliner.exhibitor', {
  url: '/{id}', 
  resolve: {
    exhibitor: function($stateParams, fair) {
      var slug = $stateParams.id;
      return slug;
    }
  },
  views: {
    'header': {   
      templateUrl: 'header.htm'  
    },
    'wop':{ 
      templateUrl: 'exhibitor.htm',
      controller: function($scope, exhibitor, $filter){
        $scope.fairs = $scope.fair;
        console.log($scope.fair);
        $scope.chosenexhibitor = $filter("filter")($scope.fairs, {'slug':exhibitor}, true);
       console.log($scope.chosenexhibitor);
      }
    }
  }
})

所有控制台日志都未定义。

我错过了什么?

PLUNKR

此处a Plunkr to examplify the issue

1 个答案:

答案 0 :(得分:0)

我想说,这个概念应该有用......只是:

  

控制器属于视图。不是所有views: {}

E.g。这个(错误)

// each view can have controller, 
// but views : {} property 'controller' is not used at all
views: {
    'header': {   
      templateUrl: 'header.htm'  
    },
    'wop':{ 
      templateUrl: 'exhibitor.htm',
    },
    controller: function($scope, exhibitor, $filter){
      $scope.fairs = $scope.fair;
      console.log($scope.fair);
      $scope.chosenexhibitor = $filter("filter")($scope.fairs, {'slug':exhibitor}, true);
      console.log($scope.chosenexhibitor);
    }

应该调整为:

 views: {
    'header': {   
      templateUrl: 'header.htm'  

      controller: function($scope, exhibitor, $filter){
        $scope.fairs = $scope.fair;
        console.log($scope.fair);
        $scope.chosenexhibitor = $filter("filter")($scope.fairs,  {'slug':exhibitor}, true);
        console.log($scope.chosenexhibitor);
      }
    },
    'wop':{ 
      templateUrl: 'exhibitor.htm',
      controller: ...

example,如何

  • 父母确实解决了
  • 子视图的控制器使用它

规定:

  .state('parent', {
      url: "/parent",
      templateUrl: 'tpl.html',
      resolve: {
        example: ['$timeout', function($timeout){
            return $timeout(function(){
              return {x: 1}
            },100)
        }],
      },
  })
  .state('parent.child', { 
      url: "/child",
      templateUrl: 'tpl.html',
      controller: 'ChildCtrl',
  })

子控制器

.controller('ChildCtrl', ['$scope', 'example', function ($scope, example) { 
  console.log(JSON.stringify(example));
}])

检查here