Issue
I have 2 sub-modules in my AngularJS (v1.7) app, let's call them A and B. I'm trying to import a component (with html template and controller) from module B (componentB), to be used inside the template of a component in module A (componentA).
After reading Reuse AngularJS Component in another Module (Dependency Injection), I first tried to do this by specifying componentB as a dependency of componentA and then using it inside componentA's template.
componentA.js
angular.module('A', ['componentB']).component('componentA', {...});
componentA.html
<div>
<componentB></componentB>
</div>
Unfortunately this did not work, even though componentB is correctly defined and being successfully used in module B. I also tried to specify module B as a dependency of module A, by modifying app.js
as shown below:
angular.module('A', ['B'])
.config(...
In both cases, I'm getting an
Uncaught Error: [$injector:modulerr]
I'm having a hard time finding similar questions/articles that relate to AngularJS as opposed to the newer Angular. I'm also pretty rusty with AngularJS so any help would be appreciated, thanks in advance.
Solution
It is pretty straight forward:
angular.module("moduleB",[])
.component("componentB", {
template: "<div>This is Component B from Module B</div>"
});
angular.module("moduleA",["moduleB"])
<div ng-app="moduleA">
<component-b></component-b>
</div>
The moduleA
imports components from moduleB
by declaring moduleB
as a dependency.
Module Creation vs Retrieval
Only the first module declaration should have dependencies specified.
ERRONEOUS
angular.module('moduleA', []) .controller('ctrl', /* ... */) angular.module('moduleA', ['moduleB']) .service('serviceA', /* ... */)
Declaring dependencies again will cause the controller to be unregistered.
Better
angular.module('moduleA', ['moduleB'])
angular.module('moduleA')
.controller('ctrl', /* ... */)
angular.module('moduleA')
.service('serviceA', /* ... */)
For more information, see
Answered By - georgeawg
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.