如何创建指令而不将其链接到可在任何模块中使用的特定模块,例如内置指令。
4 回答
指令或服务必须属于一个模块。您可以做的是为您的指令创建单独的模块,然后将它们注入您的主应用程序模块。这是我的设置:
window.app = angular.module('app', ['ngRoute', 'app.system', 'app.animations', 'app.cart']);
angular.module('app.system', []);
angular.module('app.animations', []);
angular.module('app.cart', []);
现在您的服务可以在它自己的模块中并从应用程序模块中调用。这基本上就是阿杰所说的。
angular.module('app.cart').factory("Cart", ['$resource', function($resource) {}]);
我想我明白OP的意思。类似于 Angular UI for Bootstrap 等库。OP 想要创建可以在其他应用程序中使用的指令等,而无需知道主应用程序名称。
你可以这样做:
angular.module("hello.world", [])
.directive('hello', function() {
return {
template: '<p>Hello, world!</p>',
restrict: 'E',
link: function (scope, element, attrs) {}
};
});
例如,另存为“hello-world.js”。
确保在页面中包含该 JS。然后在您的主要 Angular 应用程序中:
var app = angular.module("myApp", ['hello.world']);
然后在应用范围内的 HTML 中的任何位置,您都可以插入:
<hello></hello>
该指令将接管渲染带有“Hello, world!”字样的段落标签。内。
我的理解是,您可以对所有 Angular 对象(服务、工厂、提供者等)执行此操作。
简短的回答:不,这是不可能的。所有指令都必须是模块的一部分。
Angular文档说
就像控制器一样,指令在模块上注册。要注册指令,请使用 module.directive API。模块指令
没有办法在模块之外定义指令。
Angular 内置指令它们是在一个名为的模块上定义的ng
——参见源代码。
这个模块是使用 Angular 内部方法创建的setUpModuleLoader
(参见AngularPublic.js和loader.js)。
这个函数不是 Angular 公共 API 的一部分,所以你不能自己访问它。您需要在自己的模块中定义指令。任何依赖于此模块的应用程序模块都可以使用您的指令。
这是一种非常 Angular 的看待事物的方式——避免公共对象,但尽可能让事物可注入。
如果我没记错的话,甚至内置指令也属于一个模块(ng 模块)。只是您不必显式声明对它的依赖,因为它是由框架为您完成的。这就是为什么你总是必须声明一个模块,向这个模块添加指令以及在其他模块中依赖这个模块。类似的东西:
// Reusable module with directive(s)
angular.module('directives', [])
.directive('rating', function () {
...
}
// other module that rely on teh first one
angular.module('MyApp', [
'directives',
...
]);
//Module 2
angular.module('MyModuleWithDependency', [
'directives'
]);