angularjs - 如果可能的话,如何使 momentjs 不是 Angularjs 中的全局变量

标签 angularjs momentjs

阅读时我很困惑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/

相关文章:

javascript - angularjs 一个元素上的两个指令

javascript - Angular 路由漂亮 URL 错误

angularjs - ionic 在右键单击和中键单击时触发不需要的 ng-click

javascript - 从日期中减去时间 - 时刻 js

javascript - 使用 LoDash 对时间序列数据进行分组和求和

javascript - 如何将 moment.js 加载到 webpack 中

javascript - 如何根据页面位置实现 ng-show

javascript - 填充 Angular 用户界面 Bootstrap 弹出窗口

javascript - 存储日期,就好像它们是在特定时区输入的一样

javascript - 检查日期是否与重复日期匹配