Let's say that we have this:
In 'app/app.module.one' I define the dependencies for AngularJS module by passing in the 'app.module.two' module as a second parameter e.g.
var app = angular.module('app.module.one', ['app.module.two']);
My question is: can I in 'app.module.two' module make use of services and factories from 'app/app.module.one' ??
No. If you have Services that need to be used in both then you should put that code in a lower level module (like say app.module.base) and then both app.module.one and app.module.two would need to require it (app.module.base).
Related
I have two files in which I define services in my angular app, but when I try to use them both in my directive, I get an error saying the service provider is not found for whichever directive I define second. It seems like one service is overwriting the other. If I change the module definition in service2.js to myapp.services2, then it works. I would think I could add multiple factories to the same module this way. Can someone point out what I'm doing incorrectly?
service1.js:
var services = angular.module('myapp.services',[]);
services.factory('Service1', function() {
// service code
});
service2.js:
var services = angular.module('myapp.services',[]);
services.factory('Service2', function() {
// service code
});
mydirective.js:
angular.module('myappdirective', []).directive('myapp', ['Service1', 'Service2',
function(service1,service2) {
// directive code
}]);
This is from the docs:
Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. Use angular.module('myModule') to retrieve an existing module.
Found here:
https://docs.angularjs.org/guide/module
This is possible, however will be error prone, hence not recommended
Make small modification to what you are already doing
Just do not re-declare the module variable in other files other than service1.js or put the module definition to a file of its own and include these JS file in the order of Module.js, services.js, directive.js then it will work
I have several directives and factories spread over several files but I want all of them to be included inside the same module. For example:
user-account.js
var userModule = angular.module("user", []); //I create the module here
userModule.directive("userPicture", ...);
user-transactions.js
var userModule = angular.module("user"); //I use the module here
userModule.directive("userPayment", ...);
The problem I have is for this to work I need to include the files in the right order, otherwise it won't work since the creation of the module is only done in user-account.js. I don't like this since users for these modules would need to know the proper order for it to work.
So my question is, how can I structure my modules creation + usage in an elegant way? I was thinking on creating some kind of Singelton helper to create the module if it doesn't exist but I don't love the idea. Any other ideas?
Don't mix the user module and the user-account in the same file.
app.js:
angular.module('myApp', ['user']);
user.js:
angular.module('user', []);
user-account.js:
angular.module("user").directive("userPicture", ...);
user-transactions.js:
angular.module("user").directive("userPayment", ...);
And then in your index.html:
<!-- modules -->
<script src="js/app.js"></script>
<script src="js/user.js"></script>
<!-- directives -->
<script src="js/directives/user-account.js"></script>
<script src="js/directives/user-transactions.js"></script>
I would suggest using requirejs in that case. Then you won't have to worry about ordering of your script files.
I am following the style from the book Mastering Web Application Development with Angularjs, the link is the whole example explained in the book.
The main idea of this style is
1. Dived code by businsess feature instead of by type;
2. Put everything from one module into one file, like:
// myApp.js
angular.module('myApp', ['user']);
//user.js
angular.module('user', [])
.directive("userPicture", ...);
.directive("userPayment", ...);
//index.html:
<script src="js/app.js"></script>
<script src="js/user.js"></script>
Why doing that is no matter directives, service or controllers, they are talking to each other, in one file you don't need to switch files.
Yes, you may bloat up the model file, but it is good sign to separate into another model.
I am using that style in my projects, and I found the code much readable than before.
I'm trying to use a vertxbus module. It's configuration is set using .value.
How do I update these configuration values from my 'appModule'?
To my understanding
angular.module('knalli.angular-vertxbus')
should return a reference to the module and .value should change the injected value.
I've created a jsFiddle and here is the js used:
'use strict';
var testmodule = angular.module('TestModule', []).value('key', 'module').value('key', 'module2');
testmodule.factory('MyService', ['key', function (key) {
return key;
}]);
var module = angular.module('myApp', ['TestModule'])
.run(function () {
testmodule.value('key', 'run1');
angular.module('TestModule').value('key', 'run2');
}).controller('MyCtrl', ['$scope', 'MyService', 'key', function ($scope, MyService, key) {
$scope.value = MyService;
$scope.key = key;
}]);
I would expect a result of run2 or at least run1 but module2 is returned. Why?
The actual idea behind .value, .constant or more generally .config is the possibility to change how the modules' components should constructed themselves.
In that case, the angular-translate's vertxBus component will invoke implicitly a SockJS instance which connects implicitly to a server. That means the configuration settings must be known before the application will be running. Because of this, there are two phases (see answer by Ilan Frumer): config and run.
However, because .value and .config are too static and could collide with other components, the angular module angular-vertxbus has an own provider for all the settings (since version 0.5: https://github.com/knalli/angular-vertxbus/releases/tag/v0.5.0).
Starting with 0.5, this could be look like this:
var module = angular.module('app', ['knalli.vertx-eventbus']);
module.config(function(vertxEventBus) {
vertxEventBus.useDebug(true).useUrlPath('/eventbus');
});
Just like the others, the provider is only available in the config-phase.
Disclaimer: I'm the author of angular-vertxbus
$provide shorthands
Under the hood, constant & value & service & factory & provider are all shorthands for the $provide service which is available only during the configuration phase.
From angular.js documentation:
A module is a collection of configuration and run blocks which get applied to the application during the bootstrap process. In its simplest form the module consist of collection of two kinds of blocks:
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.
your case:
You cannot register providers (in your case value) inside run blocks because they are only available during the configuration phase.
Read more about modules and $provide
i've made an reusable module for angularJS. The module is manipulating templates inside the run function. Before its gets fully initialized i need to set various properties. In which function should i expose this properties ?
In my Angular-1.2 apps to configure the ngRoute's service I use a config block like this
app.config(function ($routeProvider) {
$routeProvider....
});
I think you could do the same by adding a service provider into your module.
Another solution would be to make your run block depend on a constant that would be defined from your application.
// In your module
foo.run(function (fooConfig) {
var url = fooConfig.url;
...
});
// In your app
app.constant('fooConfig', { url: ... });
Both solutions are demoed here : http://jsfiddle.net/JQ4Gm/
I should expose my "properties" inside a provider and access them inside config. Usage of provider.
This question already has answers here:
When should I use require() and when to use define()?
(5 answers)
Closed 5 years ago.
In RequireJS, what is the basic difference between using require() Vs define();
require(['a'], function(a) {
// some code
});
// A.js
define(['b','c','d','e'], function() {
//some code
});
Any use cases would be very helpful..
One core difference that annoyed me in early use was figuring out that a define might never be called.
As long as there is only one define per file, it will register that module as available under that filename. However, define modules are only loaded once a require function asks for each of them.
Define: If you need a XXX, then load these other things first, then return the result of this function.
Require: Load these other things, then run this function. (no "if")
Example: Let's say you include this JS file in your page:
// this is in company/welcomepage.js
define(['company/ui_library'],
function(uiLib) {
console.log('Welcome to {company}!');
}
);
If that's the only Javascript file, you could open your page, and there would be nothing in the console log, in spite of the script telling it to welcome the user. However, that changes if somewhere in the page, or in another script, you insert the following:
require(['company/welcomepage'], function() {
// optionally insert some other page-initialization logic here
});
Now, the page will put a welcome message in the console when it loads.
In fact, with that second one in place, there would be no need to manually include welcomepage.js as a <script> tag; it would load it from its location as soon as it sees the require, and realizes it needs it.
require and requirejs are the same.
require === requirejs // true
require is a way to load a module which has been defined. For example to load the logger module I could do:
require(["logger"], function(logger){
logger.bla("S");
});
Here i am calling require, specifying an already defined module called logger and using it by calling its bla method.
define is a way to define a module. For example to define a logger module I could do:
// logger.js
define(function(){
return {
bla: function(x){
alert(x);
}
}
});
Here i called define and defined the logger module. in this module I returned the bla function i want to expose.
Sometimes define looks very similar to exports because define can also depend and use other modules just like require can use other modules. Let me show you the same logger module, this time using a module
// logger.js
define(["popup"], function(popup){
return {
bla: function(x){
popup.show(x);
}
}
});
Here the logger module I defined, also has a dependency called popup and thus it looks like require.
I believe you always use define for your module definitions. You have several flavours to do so, you can define a module with its dependencies in an array as the first argument to define (as in the example you posted).
Or you can use the Simplified CommonJS wrapper, something like this:
define(function (require) {
var otherModule = require('otherModule');
return function () {
return otherModule.operation();
};
});
Maybe you got mixed up with the JSONP service dependency format, which uses require() to load the service, and then specify define() as the JSONP callback which will eventually define the module once the service responds.
So in the end, you use define() to define modules, and require() to load them.
define is how we declare a module, in accordance with AMD module format(there are other available module formats like CommonJS, ES2015, System.register, UMD)
whereas ..
require is a module loading construct that's available with module loaders like RequireJs, SystemJS, Node's built-in module loader. It is used when you want to use a module defined in one of the above-stated module formats.
require() and define() both used to load dependencies.There is a major difference between these two method.
Its very Simple Guys
Require(): Method is used to run immediate functionalities.
define(): Method is used to define modules for use in multiple locations(reuse).