在AngularJs中设置全局常量 [英] Set global constants in AngularJs

查看:369
本文介绍了在AngularJs中设置全局常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为应用程序在angular js中创建常量js文件。我正在使用以下代码为整个应用程序实现常量。

I am trying to create constants js file in angular js for an application. I am using below code to implement constants for entire application. It's working fine.

<code>
// app.js
angular.module('myApp', [
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'ngRoute'
    ])
    .constant('config', {
        mySetting: 42
    })
    .config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });
    });
</code>

我关心的是app.js文件,我只想写路由,要写的常量单独的文件,我将为应用程序中的所有控制器调用同一文件。

My concern is in app.js file I want to write only routing, for constants I want to write separate file and I will call same file for all the controllers in my application.

对于整个应用程序,我可能要声明200个以上的常量,因此我想使它成为单独的文件或为控制器明智地拆分常量文件。

For entire application might be 200+ constants I want to declare, so I want to make it is separate file or split constants file for controllers wise.

请指导我哪种方法易于维护。

Please guide me which way is easy for maintenance.

预先感谢

推荐答案

您还可以通过使用另一个模块来处理所有常量,工厂,服务或价值来维护单独的文件。为了处理您的常量,下面的代码将给您和提示

You can also maintain a separate file by using another module to handle all your constant, factory, services or value. To handle your constants the below code will give you and idea

例如:

包括您的 app.js 文件,然后是您的 constant.js 脚本文件

include your app.js file after that your constant.js script file

var myApp = angular.module("myApp", ['myConstants']); //constants module injection
myApp.controller("myController", ["$scope", "myValue", function() {
....
}]);

在您的constant.js中

in your constant.js

angular.module("myConstants", []).constant('myValue', 'The value');

要了解更多信息,请参考 http://www.learn-angular.org/#!/lessons/handling-complexity

For more understanding refer http://www.learn-angular.org/#!/lessons/handling-complexity

这篇关于在AngularJs中设置全局常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆