如何在一个文件中定义常量,并在angularjs中访问另一个文件
我在我的应用程序中处理很多variables,我不想每次都定义string。 而不是我想从一个文件访问string,并访问我的应用程序中的所有文件。
例如:
one = 1;
我想在我的应用程序中访问variables名1,因为将来它可以作为一个(一个=一个),我不能改变所有的地方。
为了避免这样的困难,我要为恒定的文件。
您可以创build一个服务并通过注入来访问它。
angular.module('app') .constant('CONSTANTS', {something: 12});
你的控制器
angular.module('app').controller('mainCtrl', function (CONSTANTS) { $scope.mainctrlvariable = CONSTANTS.something; });
你另一个控制器
angular.module('app').controller('otherCtrl', function (CONSTANTS) { $scope.otherCtrlvariable = CONSTANTS.something; });
Angular提供常量和值服务,可以帮助你
'use strict'; angular .module('App', []) .constant("config", { one:1, two:2 }) .config(function () { }) .controller('MainCtrl', function (config) { console.log(config.one) });