I want to use a provider to set some configuration settings at starting up my AngularJs app, but I would like to have the app and the provider in 2 seperate files.
This is how I have it now:
var myApp = angular.module('myApp', []);
myApp.config(function(myServiceProvider) {
....etc.
The provider is defined like this:
angular.module('myApp').provider('myService', function () {
...etc.
If I load the app first the provider is not there yet, and if I load the provider first the app is not there yet.
What would be the best way to solve this?
Your module definition includes module dependencies - not services or providers.
It should be:
var myApp = angular.module('myApp', []);
The config block is always executed after your providers are initialized. There is no circular dependency issue.
File 1: Define module
angular.module('myApp', []);
File 2: Define providers
angular.module('myApp').provider('myService',function() {...});
File 3: Define config block
angular.module('myApp').config(function(myServiceProvider) { ... });
HTML:
<script src="/angular.js"></script>
<script src="/file1.js"></script>
<script src="/file2.js"></script>
<script src="/file3.js"></script>
Order of the files is important.
in your first file:
var myApp = angular.module('myApp', []);
myApp.config(function(myServiceProvider) {
....etc.
and in your second file:
myApp.provider('myService', function () {
...etc.
The variable myApp is a global variable and you can access to this everywhere in your website.
You can take a look at the Yeoman project, it's a generator which create your angularjs app structure and add lot of cool features.
Related
I am doing angular project,i have a situation that i need to load "ngSanitize" module.The problem is i don't need this module when index page loading.I want to load it only when required.Please help to find out.
Create a seperate module file (app.module.js) in application depends on your requiement...
angular.module("SampleOne", []);
angular.module('SampleTwo', []);
angular.module("SampleThree", []);
angular.module("SampleFour", []);
angular.module('SampleFive', []);
On page loading initialize this module file,
Depends on your requirement call the modules in your application.
Here "SampleFive" is one of the module i have injected ngSanitize.
var app = angular.module('SampleFive', ['ngSanitize'])
app.controller('MyController', function ($scope) {
$scope.Message = "My name is <span><b>Angular Sanitize</b></span>";
});
When we will call "SampleFive" module on a page only ngSanitize module will load.
Refer a below link...
AngularJS Best Practices: Directory Structure
I'm getting this error when using the recommended component loading method (See step 3 )
Error: Module name "angular-ui-router" has not been loaded yet for context: _. Use require([])
app module definition:
<script>
var adminApp = angular.module('adminClientApp', [require('angular-ui-router'), 'ngMaterial', 'ngResource', 'ngMessages', 'ngMdIcons']);
</script>
According to the doco, there isn't a need to include a script tag - it will be loaded via requirejs
Requirejs main.js definition:
require.config({
paths:{
'angular-ui-router': 'vendor/angular-ui-router/release/'
},
shim:{
'angular': {
exports: 'angular'
}
}
});
app layout:
-- root
index.html
main.js
-- js
-- app (angular files here)
app.js
-- vendor (3rd party libs)
requirejs main.js setting in index.html
<script data-main="main.js" src="vendor/requirejs/require.js"></script>
The guide you are using is not made for RequireJS. After applying the instructions there, you are doing something like this:
<script>
var myApp = angular.module('myApp', [require('angular-ui-router')]);
</script>
This will generally fail to work with RequireJS because calling require with a single string fails unless the module is already loaded. This call is guaranteed to work only if it is inside a define, like this:
define(function (require) {
var myApp = angular.module('myApp', [require('angular-ui-router')]);
});
This code is a module which should be in a separate .js file and loaded with require(['module name']). (Note that the parameter is an array of strings. This is a different form of require than the one that takes a single string parameter.)
You should use Component, which is what the author of the guide you are using was using when he/she wrote the guide, or a tool that is equivalent to it. Otherwise, you need to convert your code to work with RequireJS.
I have a page containing multiple containers. Each container will have its own controller but point to one factory, which handles all the logic interacting with a web service API. I would like to have a separate file for each controller BUT I want all of this inside of one module. for the life of me I cannot find how to include controllers from different files into one modules.
//file 1
MyController ....
//file 2
MyOtherController
//file 3
MyFactory
//file 4
The Module
The module would be composed of MyController, MyOtherController and MyFactory defined in three separate files. Can someone help with this or point me to a good resource? Thanks!
You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc. To access a container just call its module name for example
//file.4
angular.module("theModule",[]);
now that you have declared main module within angular now you can access mainModule from anywhere using angular
//file 1
angular.module("theModule").controller("MyController",[function(){...}]);
//file 2
angular.module("theModule").controller("MyOtherController",[function(){...}]);
//file 3
angular.module("mainModule").factory("MyFactory",[function(){...}]);
Check out the documentation for more information.
I also suggest reading Google's style guide and conventions manual
Also read about setting up app structure for maintainability
Here is a example of an Angular module setup I am using in an app that allows a separate external file for each module type. Note that the app must load before the external files. Tested on Angular 1.4.9.
Index.html
<script src="bower_components/angular/angular.min.js"></script>
<script src="js/ng-app.js"></script>
<script src="js/ng-factories.js"></script>
<script src="js/ng-directives.js"></script>
<script src="js/ng-controllers.js"></script>
ng-app.js
var app = angular.module('myApp', [
'factories',
'directives',
'controllers'
]);
ng-controllers.js
//note: I am injecting the helloFac factory as an example
var ctrl = angular.module('controllers', []);
ctrl.controller('MyCtrl', ['$scope', 'helloFac', function($scope, helloFac) {
console.log(helloFac.sayHello('Angular developer'));
}]);
ng-directives.js
angular.module('directives',[])
.directive('test', function () {
return {
//implementation
}
})
.directive('test2', function () {
return {
//implementation
}
});
ng-factories.js
var factories = angular.module("factories", []);
factories.factory('helloFac', function() {
return {
sayHello: function(text){
return 'Hello ' + text;
}
}
});
I'm learning AngularJS following an organization inspired by ng-boilerplate. I create different Angular modules for the different parts of my site.
However, I want to create all common elements (services and directives) under the main module, while having them all be in separate source files.
This code works, but is the module in sessionService.js referencing the same module than app.js, or is it creating a new one with the same name?
app.js
var app = angular.module('myApp', [...])
.config(...)
.controller(...);
sessionService.js
angular.module('myApp', [])
.service('SessionService', function() { ... });
If you call angular.module('myApp', []) multiple times on the same page, you will likely run into errors or conflicts. I never tried that.
However, if you already run angular.module('myApp', []) once. Then you can run angular.module('myApp') (note: without []) to retrieve (refer to) the myApp module you defined earlier.
in controller.js file :
var app = angular.module('myApp',['newService']);
in service.js :
angular.module('newService',[])
.service('someService',function(){
return {
// return something
return null
}
}
});
Do not forget to include both the js files in your HTML:
<script src="controllers/controller.js" type="text/javascript"></script>
<script src="services/service.js" type="text/javascript"></script>
Naming & namespacing is important in any project. Try:
app.js:
var app = angular.module('myApp', ['sessionService', ...])...;
sessionService.js:
angular.module('sessionService', [])
.service('SessionService', ...);
Notice that the module name is in lower camel case while the service object itself is upper camel case. This will help you avoid namespace clashing. Hope that helps.
In some AngularJS tutorials, angular app is defined as:
myApp = angular.module("myApp",[]);
But we can also do without it. The only difference I can see is when we define controller, we can't use idiom:
myApp.controller("myCtrl",function(){ })
but has to use
function myCtrl (){}
Is there any other benefits of defining myApp explicitly, given that I will only create a single app for my site? If I don't define myApp, then where my modules are attached to?
If there is, how I can recreate myApp in testing with Jasmin?
You can define controllers in (at least) 3 ways:
Define the controller as a global var (stored on the window object)
function Ctrl() {}
which is the same as doing:
window.Ctrl = function () {}
Create a module and use the returned instance to create new controllers:
var app = angular.module('app', []);
app.controller('Ctrl', function() {});
Create the controllers directly on the module without storing any references (the same as 2 but without using vars):
angular.module('app', []);
angular.module('app').controller('Ctrl', function() {});
From Angular's point of view, they all do the same, you can even mix them together and they will work. The only difference is that option 1 uses global vars while in options 2 and 3 the controllers are stored inside an Angular's private object.
I understand where you're coming from since the explanation for bootstrapping your Angular is all over the place. Having been playing with Angular only for a month (I'll share what I know anyways), I've seen how you have it defined above. I was also in the same scenario where I only have to define myApp once and not have multiple ones.
As an alternative, you can do something like this below. You'll notice that the Angular app and the controller doesn't have to live by the same namespace. I think that is more for readability and organization than anything.
JS:
window.app = {};
/** Bootstrap on document load and define the document along with
optional modules as I have below.
*/
angular.element(document).ready(function () {
app.ang = angular.bootstrap(document, ['ngResource', 'ngSanitize']);
// OR simply, works similarly.
// angular.bootstrap(document, []);
});
/** Define Angular Controller */
app.myController= function ($scope, $resource, $timeout) {
};
HTML:
<div role="main" ng-controller="app.myController"></div>
you have to define the app with angular.module anyway. myApp.controller and function myCtrl are the same..