AngularJS在Application .run方法上设置Variable。后来在控制器,服务,html中使用

时间:2014-02-22 19:42:22

标签: angularjs

我需要为填充了$ http.get(url);

的应用设置全局配置变量
    .run(['$http', '$rootScope','rootService', function($http, $rootScope, rootService) {

    rootService.getApplicationConfig().success(
        function(data, status) {
            $rootScope.appSettings = data;
        }
    );

我可以在{{appSettings.SomeValue}}的html中使用它。 .run方法在.config之后执行的问题。在控制器中,appSettings未定义。

如何在控制器中使用它?或者创建全局变量,只有在启动时才会填充。

4 个答案:

答案 0 :(得分:1)

不要使用此代码

这很棘手 我从来没有把这个代码放在我的应用程序^^ 我发现的唯一方法是:

'use strict';
            angular.module('app', [])
            .config(function () {

           })
           .run(function($rootScope,$timeout,Myconfig){
                $rootScope.config = {};
                Myconfig.get().then(function(data){   
                   $rootScope.config = data;
               });
           })
           .factory('Myconfig', function ($http,$q) {
                return {
                    get : function() {
                        var deferred = $q.defer();
                        $http.get('config.json')
                            .success(function (response) {
                                deferred.resolve(response);
                            })
                            .error(function(data, status, headers, config) {
                                deferred.reject([]);
                        });
                        return deferred.promise; 
                   } 
                }
          })
          .controller('MainCtrl',function($scope){
            $scope.$watch('config',function(){
                console.log($scope.config);
            });

          });

如果您关注控制台,您可以意识到 你不能在prod中使用这个代码,至少我没有 找到任何使用promise来检索配置 来自服务器。

<强>更新 我想这是你的服务器 写服务器端配置js 喜欢

var config = {prop:1};

包含在您的信息页中 而不是简单地做

app.constant('CONFIG',config)

<强>更新

伪代码

我想到的唯一合理的事情是:

$routeProvider.when('/', {
    controller: 'MyCtrl',
    resolve: {
        config: function(rootService) {
            return rootService.getApplicationConfig()
        }
    }
})

app.controller('MyCtrl', function ($scope,MyService,config) {
    MyService.set(config);       
});
app.controller('MyCtrl', function ($scope,MyService) {
    MyService.get();       
});

答案 1 :(得分:1)

注意:不要使用.run()。该方法运行异步,您不会总是拥有数据!

提供程序与 AppController 一起使用。

示例:

声明(在app.js中执行此操作):

angular.module('app', ['ui.router'])
.value('appSettings', { myValue: undefined })

appSettings 现在是一种可注射服务。使用方式如下:

angular.module('ctrls.myCtrl', [])
.controller('myCtrl', ['appSettings', function(appSettings) {
    console.log(appSettings.myValue);
}]);

在应用程序启动时从服务器资源设置值。

声明 AppController (我通常在我的app.js中执行此操作):

.controller('appCtrl', ['rootService', 'appSettings', function (rootService, appSettings) {
var vm = this;
vm.loaded = false;

if (appSettings.myValue == undefined) {
    rootService.getApplicationConfig().success(
       function(data, status) {
           appSettings.myValue = data;
           vm.loaded = true;
       }
   );
}}]);

在主html页面的正文中( boot css类显示某种加载屏幕):

<div ng-controller="appCtrl as vm">
    <div class="boot" ng-show="!vm.loaded"></div>
    <div ng-if="vm.loaded" ui-view="main" role="main" class="main"></div>
</div>

只有在 appCtrl 加载了您的服务器设置后,应用程序中的其他控制器才会加载到ui-view =&#34; main&#34;中。这样您就可以随时使用appSettings。

答案 2 :(得分:0)

找到具有“价值”的解决方案

    .value('appConfig',{
            apiUrl: '/api',
            settings: null
    })

    .run(['$http', '$rootScope','rootService','appConfig', function($http, $rootScope, rootService,appConfig) {

        console.log(appConfig);
        appConfig.settings = 'we can change it';
        console.log(appConfig);


}])

答案 3 :(得分:0)

最后找到了如何只制作一次JSON的答案!

app.js 中的

,其中app = angular.module add

    $provide.factory('appConfig', function ($q,rootService) {
        return rootService.getApplicationConfig();
    });

<强> rootService.js

angular.module('projectApp').service('rootService', ['$http','$routeParams','API_URL',function ($http, $routeParams, API_URL) {
    return {
        getApplicationConfig: function() {
            var url = API_URL+'/config/settings.json';
            console.log(url);
            return $http.get(url);
        },
    };

}]);

终于在您的控制器中执行此操作

angular.module('projectApp').controller('MainCtrl', ['$location','$scope','$routeParams','rootService','appConfig', function ($location, $scope, $routeParams, rootService, appConfig) {

    $scope.content = false;
    appConfig.success(
        function(data, status) {
            console.log(data.time);
            $scope.content = JSON.parse(data.config_homepage).content
        }
    );

}]);

在服务器端,我将时间推送到我的JSON。每次我使用“appConfig”时都显示同一时间。这意味着请求只进入服务器一次。


如果有人有更好的解决方案,请将其作为回答发布