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

前端之家收集整理的这篇文章主要介绍了如果可能的话,如何使momentjs不是Angularjs中的全局变量前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
阅读 Angularjs style guide Y240时我很困惑.

它讨论了为供应商库的全局变量创建角度常量,以便我们可以注入原本为全局变量的供应商库.

我的理解是你必须这样做:

<script src="moment.js"></script>

在app.js中加载angular.js和控制器和指令之前,moment对象是一个全局变量.如何使用以下代码使其成为服务,并在需要时注入?

如果我没看到全貌,请纠正我.

// 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();
}]);

更新

时刻仍然是一个全球变量.

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相关文章