阅读时我很困惑Angularjs style guide Y240 .
它讨论了为供应商库的全局变量创建一个 Angular 常量,以便我们可以注入(inject)否则是全局的供应商库。
我的理解是你必须这样做:
<script src="moment.js"></script>
在 app.js 中加载 angular.js 和 Controller 和指令之前,moment 对象是一个全局变量。如何使用下面的代码使其成为服务,并且可以在需要时注入(inject)?
如果我没有看到完整的图片,请纠正我。
// constants.js
/* global toastr:false, moment:false */
(function() {
'use strict';
angular
.module('app.core')
.constant('toastr', toastr)
.constant('moment', moment);
})();
我的困惑:
上面的代码应该使全局变量“时刻”不是全局的。它是否正确?我认为这是不可能的。时刻仍然是全局变量。
最佳答案
要在 AngularJS 应用程序中使用以这种方式创建的常量:
//declare 'app.core' as a dependency
angular.module('myApp', ['app.core']);
//declare the constant in your injection list
angular.module('myApp').controller('myController', ['$scope', 'moment',
function($scope,moment) {
//use moment as you would normally
var now = moment();
}]);
更新
moment
仍然是一个全局变量。John Papa 这样做的原因:
Why?: Provides a way to inject vendor libraries that otherwise are globals. This improves code testability by allowing you to more easily know what the dependencies of your components are (avoids leaky abstractions). It also allows you to mock these dependencies, where it makes sense.
https://github.com/johnpapa/angular-styleguide#style-y240
关于angularjs - 如果可能的话,如何使 momentjs 不是 Angularjs 中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34280389/