gpt4 book ai didi

javascript - 在angularjs中注入(inject)依赖项的可维护方式

转载 作者:行者123 更新时间:2023-11-30 16:48:55 26 4
gpt4 key购买 nike

我想知道如何以更具可读性的方式注入(inject)依赖项。我对 AMD(requirejs) 方式更感兴趣。喜欢以下内容:

define(function (require) {
var ModuleOne = require("ModuleOne"),
ModuleTwo = require("ModuleTwo");

var ThisModule = (function () {
// code here
})();

return ThisModule;
});

是否可以在 angularjs 中以上述方式注入(inject)依赖项,或者是否有比 angularjs 中当前方式更好的方式来做到这一点?

最佳答案

来自 Angular JS official website

Angular modules solve the problem of removing global state from the application and provide a way of configuring the injector. As opposed to AMD or require.js modules, Angular modules don't try to solve the problem of script load ordering or lazy script fetching. These goals are orthogonal and both module systems can live side by side and fulfil their goals.

因此,这两个库(RequireJS 和 AngularJS)的用途完全不同。 AngularJS 内置的依赖注入(inject)系统处理组件中所需的对象;而 RequireJS 中的依赖管理处理模块JavaScript 文件

在 requireJS 中,加载模块的对象被缓存,并在再次请求相同模块时提供它们。另一方面,AngularJS 维护一个带有名称列表和相应对象的注入(inject)器。在这种情况下,只要使用注册名称引用对象,就会提供对象。

通常我们在angularJS中注入(inject)依赖

someModule.controller('MyController', function($scope,greeter){

});

如果你想要一种替代方法来在 angularJS 中注入(inject)依赖项,你可以做类似的事情。

var MyController = function($scope, greeter) {
// ...
}
MyController.$inject = ['$scope', 'greeter'];
someModule.controller('MyController', MyController);

希望对您有所帮助!

关于javascript - 在angularjs中注入(inject)依赖项的可维护方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30817199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com