Angular 1 / Ui-router - 将数据从resolve传递给控制器​​

时间:2017-09-18 09:09:17

标签: javascript angularjs routes angular-ui-router

我想通过解决方案将数据(contactName)从状态传递给控制器​​:

.state({
      name: 'contact.detail.overlay',
      abstract: true,
      component: 'overlayContent',
      resolve: {
        contactName: (originalContact, $rootScope, ContactService) => {
          $rootScope.contactName = ContactService.getContactName(originalContact)
          return $rootScope.contactName
        }
      }
    })

在我的状态上一切正确,contactName也是正确的,但我的overlayContent控制器无法访问它,您是否有解决方案在控制器中拥有$rootScope.contactName访问权限?

编辑: 控制器:

class overlayContentComponent {

  constructor($state, $interpolate, $scope) {
    'ngInject'
    this.$scope = $scope
    this.$state = $state
    this.$interpolate = $interpolate
  }

  /**
   *
   * On initialization hook, let's check if an overlay title
   * has been defined for the current state.
   */

  $onInit() {
    const stateData = this.$state.current.data || { title: '' }
    this.overlayTitle = angular.isDefined(stateData.title) ? this.$interpolate(stateData.title)() : ''
  }
}

export const overlayContentComponent = {
  template: require('./overlay-content.html'),
  controller: overlayContentComponent
}

我可以通过contactName访问我的控制器中的this.$scope.$root.contactName,但我希望通过其他替代方式避免$scope.$root

1 个答案:

答案 0 :(得分:0)

更改构造函数:

constructor($state, $interpolate, $scope, contactName) {
  'ngInject';
  // The variable you want:
  this.contactName = contactName;
  this.$scope = $scope
  this.$state = $state
  this.$interpolate = $interpolate
}

现在应该将'contactName'解析注入该状态的控制器(解析所在的位置)。这应该允许您在控制器中访问它,如上所述。