向angularjs应用程序添加常量

时间:2014-01-26 16:38:48

标签: javascript angularjs

我正在尝试向angularjs应用程序添加常量,但是我得到了未定义的错误。

var appConstants = {

};

var appErrorMsgs = {
    loginFail: "Login failed, please check your credentials"
};



var URI_PATH = {
    registration: "/registration",
    seasons: "/seasons",
    vip: "vip",
};

angular.module('app.constants', []).
    constant('CONST', appConstants).
    constant('ERROR_MSG', appErrorMsgs).
    constant('URI_PATH', URI_PATH);

var app = angular.module('AppName', ['snap', 'ngRoute','ngResource','ngTouch','angular-carousel','FSControllers', 'FSPartials','FSDirectives', 'kinvey', 'app.constants']);

2 个答案:

答案 0 :(得分:6)

我猜你只是忘了注射它们:

这是一个吸虫:http://plnkr.co/edit/4gav6PvJtPwJExchya2i?p=preview

app.controller('MainCtrl', function($scope, URI_PATH, ERROR_MSG, CONST) {
  console.log(CONST);
  console.log(ERROR_MSG);
  console.log(URI_PATH);
});

答案 1 :(得分:-1)

我猜建议的解决方案是使用服务:

angular.module('AppName').factory('app.constants', [buildConstants]);
function buildConstants(){
    var appConstants = { };

    var appErrorMsgs = {
            loginFail: "Login failed, please check your credentials"
        };

    var URI_PATH = {
        registration: "/registration",
        seasons: "/seasons",
        vip: "vip",
    };

    return {
        CONST: appConstants,
        ERROR_MSG: appErrorMsgs,
        URI_PATH: URI_PATH
    };
}

然后您可以根据需要将其注入控制器和指令中。 希望这会有所帮助。