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

时间:2022-08-24 17:37:09

I want to pass a data (contactName) from the state to the controller by the resolves :

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

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

on my state all is correct, contactName is also correct, but it is not accessible in my overlayContent controller, do you have a solution to have $rootScope.contactName access in the controller ?

在我的状态都是正确的,contactName也是正确的,但是我的overlayContent控制器无法访问它,你有解决方案在控制器中有$ rootScope.contactName访问吗?

EDIT : The controller :

编辑:控制器:

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
}

I can access contactName in my controller by this.$scope.$root.contactName but I would like to avoid $scope.$root by another alternative

我可以通过这个访问我的控制器中的contactName。$ scope。$ root.contactName但是我想避免使用$ scope。$ root by another alternative

1 个解决方案

#1


0  

Change your constructor:

更改构造函数:

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

The 'contactName' resolve should be injected now, into the controller for that state (where the resolve resides). This should allow you to access it in the controller, as above.

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

#1


0  

Change your constructor:

更改构造函数:

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

The 'contactName' resolve should be injected now, into the controller for that state (where the resolve resides). This should allow you to access it in the controller, as above.

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