use angular.js directives in different applications? - javascript

I have a directive that I want to use in various places.
var app1 = angular.module("App1"...);
app1.directive('ngFoo' ... );
other Webpage:
var app2 = angular.module("App2"...);
app2.directive('ngFoo' ... );
How can I add the code of the directive in a practical way in different pages?
What is there best practice?

What you are looking for is a module pattern, that creates the ability to reuse code easily. If the directive is the same for app1 and app2 i suggest to create your own module for the directive:
angular.module('myDirectiveModule', []).directive('ngFoo', ...);
Then, if you want to use the directive in app1 you include it as dependency of your app1 module:
angular.module('app1', ['myDirectiveModule']);
You can then just go ahead and use the directive in app1. The same is true, if you want to use the directive in app2:
angular.module('app2', ['myDirectiveModule']);
So the directive becomes it's own reusable module.

Related

Angular component relative templateUrl

I'm developing a modular angular application with I defined I folder path (constant : BASE_PATH : "path/to/folder") in angular-module-1 module. I want to re-used this constant in a angular component located in another module (angular-module-2)of my application. I want to use this constant many time in my project.
module.component("relationshipSearch", {
templateUrl: BASE_PATH +'/link/to/other/folder',
witch is the best way to define this constant as a global variable visible in all the solution project
Here is my project structure:
project
|-- angular-module-1
| |-- angular-module-1.js
| |-- angular-module-1.html
|-- angular-module-2
| |-- angular-module-2.js
| |-- angular-module-2.html
I'd say that create a common module named as angular-common where you can place common stuff like common service, factory, directive, constants, etc.
Then add the constant inside angular-common(this would be completely independent and plug-able) module. like below
//assuming `angular-common` is already defined
angular.module('angular-common').constant('commmonSetting', {
'BASE_PATH': '/link/to/other/folder'
})
Next, inject this common module in app(which is main module, going to be used in ng-app/bootstrap) like below
angular.module('app', ['angular-common', 'ngRoute', ...other dependencies..])
When you wanted to use BASE_PATH just inject commmonSetting dependency in controller/component wherever you want.
app.component('myComponent', {
templateUrl: function(commmonSetting){
return commmonSetting.BASE_PATH +'/link/to/other/folder';
},
....
})
Sorry, for posting on an old thread with an accepted answer, but I wanted to say that the accepted answer is not minification safe. The minification safe way to write this is:
app.component('myComponent', {
templateUrl: function($injector){
var commmonSetting = $injector.get('namespace.CommmonSetting');
return commmonSetting.BASE_PATH +'/link/to/other/folder';
},
....
});
Perhaps a different approach might help. Instead of setting the path why not just look to a file in the same directory.
You could use require(), for example:
template: require('./template-in-same-dir.html')
Note the template not templateUrl.

Inject angularjs directive

I have this structure in my script A:
module.exports = angular.module('myApp').controller(..).directive(..)
I want to inject additional directive so that I have something like this:
module.exports = angular.module('myApp').controller(..).directive(..).directive(..)
I want to do this from the outside of the script A.
Any ideas how this can be achieved? I am still catching up with the angular, and any help is really appreciated! Thanks a lot!
If I understand correctly, you want to create your directive dynamically. (within different angular module) You can code in the way blow,
//dynamic directive dyDir.js
module.exports = function (app) {
app.directive(...)
};
your script
var dyDir = require('./dyDir.js');
var yourApp = angular.module('appName',[]);
yourApp.controller('testCtrl', ...)
dyDir(yourApp); //parse angular module instance as parameter
Although this would work, but I really don't think use angular.module and the commonjs module at the same time is a good practice, coz this would make the other developer so confused.
Hope this would solve your problem. : )
I got this solved in a following way - if it can be of any help to anyone:
Assume you have an existing module myModule, and two controllers myController1 and myController2 (code for the two controllers is in files controller1.js and controller2.js). This is your code in a file myapp.js:
module.exports = angular.module("myModule", [])
.controller('myController1', require('./controller1.js'))
.controller('myController2', require('./controller2.js'))
Assume you would like to inject additional directive into your module myModule. You would reuse that module.
You would create a new file with the following content:
require('./myapp.js');
require('./mydirective.js'); //this is your new directive
var app = angular.module("myModule"); //get an existing module
app.directive('directiveName', function() {
return {
...
}
})

Should AngularJS modules be in their own file?

Fairly simple question, I can't seem to find a definitive answer. At the minute I've my module declared in one file :
var module = angular.module("app", ["agGrid", "ngAnimate", "ngSanitize", "ui.bootstrap"]);
and my controller in another :
angular.module("app").controller("mainCtrl", ["$scope", "$timeout", "dateFilter", "$http", "shareDataService", "getDataService", function ($scope, $timeout, dateFilter, $http, shareDataService, getDataService) {
Is this good structure or a waste of time and space?
Single Responsibility
Define 1 component per file.
The following example defines the app module and its dependencies, defines a controller, and defines a factory all in the same file.
Avoid this
angular
.module('app', ['ngRoute'])
.controller('SomeController', SomeController)
.factory('someFactory', someFactory);
function SomeController() { }
function someFactory() { }
The same components are now separated into their own files.
Do this
// app.module.js
angular
.module('app', ['ngRoute']);
// some.controller.js
angular
.module('app')
.controller('SomeController', SomeController);
function SomeController() { }
// someFactory.js
angular
.module('app')
.factory('someFactory', someFactory);
function someFactory() { }
https://github.com/johnpapa/angular-styleguide#style-y001
It's a good practice to keep them separate. This way, you don't end up mixing the module(s) definition and controllers / services / directives.
here you get some of the best practices in angular js -
Instead of slicing your app across horizontals that can't be broken
up, group your code into related bundles. This way if you remove a
module, your app still works.
https://github.com/angular/angular.js/wiki/Best-Practices
Having separate files for each type of component is ideal. I follow the structure in development:
app.js //where the module resides
routes.js //consists of routes
controllers/
services/
factories/
filters/
directives/
Define your module:
var app = angular.module();
Then use 'app' to declare other nested js in separate files, example:
app.directive()
However, in production, it is preferable to use task runner (eg gulp) to combine all the files and minify the final file.

angularjs defining services for the same module in different files

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

Create an AngularJS module if it doesn't exist

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.

Categories

Resources