阅读
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.