从 angular.module config 获取数据到相应的控制器

get data from angular.module config to the corresponding controller

我有以下配置,我有一个配置,其中使用 $http.get 方法调用 url,数据存储在变量 "alpha" 中。如何从控制器访问此变量。我试图将 $rootScopeProvider 注入配置并尝试设置 $rootScope.pqr = alpha。这给出了一个错误。我该怎么做?

angular.module('thisApp', [someDependencies]).config( function($stateProvider, $urlRouteProvider) {
    $http.get('url').then(function(response) {
        var alpha = response.data; // i need to access this data in the controller
    )};
}).directive('pqrTitle', function () {
    return {
        restrict: 'A',
        controller: function($scope, $rootScope) {

        // I need to access alpha here
    });
});

我该怎么做?

其实我想知道你是如何在配置阶段获得 $http 服务的。您只能根据 documentation:

配置该阶段的提供程序和加载常量

Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.

当我尝试将服务注入配置阶段时,出现以下错误:link

最好的办法是编写一个服务以从您想要的服务器获取信息并将该服务注入您的指令。 (在其他地方你需要它)

示例:(working示例更广泛)

.controller('TestController', function(alphaService) {
  var self = this;

  self.alpha = alphaService.get().success(function(data) {
    self.alpha = data;
  });
})

.factory('alphaService', function($http) {
  return {
    get: function() {
      return $http.get('url');
    }
  };
})

.directive('myDir', function(alphaService) {
  return {
    restrict: 'E',
    link: function (scope, element, attr) {
      scope.alpha = null;

      alphaService.get().success(function(data) {
        scope.alpha = data;
      });
    },
    templateUrl: 'mydir.html'
  };
});

如果你正在使用 ui-router-extras,你可以为此使用 $futureStateProvider,你也可以使用 $rootScope 并在控制器中访问它

angular.module('thisApp', [someDependencies])
.config( function($futureStateProvider, $stateProvider, $urlRouteProvider) {

    $futureStateProvider.addResolve(['$http', '$rootScope', function($http, $rootScope) {
        $http.get('url').then(function(response) {
            $rootScope.alpha = response.data;
        )};
    }]);
})

1) 在控制器中,你应该注入 rootScope 并访问变量。阅读本文以了解 $futureStateProvider in ui-router extras

2) 如果你不想使用rootScope,创建一个服务并将其注入$futureStateProvider.addResolve,在服务中设置变量。之后你可以通过一个getter函数

获取变量值

希望对你有帮助