I have looked at various examples of separating the files. I can understand them but the problem comes with the way my code is. I want separate these controllers in different files.
'use strict';
angular.module('myModule', ['ui.bootstrap']);
var myApp = angular.module('myApp', []);
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/getplaces', {
templateUrl: 'templates/getplaces.html',
controller: 'ListCtrl'
})
The below controller needs to be in a different file.
///////////// MONTHLY DATA /////////////////////////////////////
myApp.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/getmonth', {
templateUrl: 'templates/getmacs.html',
controller: 'MonthlyCtrl'
})
}])
.controller('MonthlyCtrl', function ($scope, $http) { $scope.visible = true;
})
I have more than 20 controllers like above. but how do I separate them.
Here is how you should do it,
first declaration
angular.module('appName', ['Module1', 'Module2', 'Service1']);
subsequent declarations
here all the controllers and service can be in separate files.
angular
.module('Module1', [])
.controller('AbcController', ['$scope', '$timeout', 'Service1', function ($scope, $timeout, service1) {} ]);
angular
.module('Module2', [])
.controller('EfgController', ['$scope', '$timeout', 'Service1', function ($scope, $timeout, service1) {} ]);
angular.module('Service1', [])
.service('XYZService', ['$http', function LmnoService($http) {
} ]);
This should easily be done, I would organize my application route configurations into the main app.js file.
myApp.config(['$routeProvider',
function ($routeProvider) {
$routeProvider.when('/getplaces', {
templateUrl: 'templates/getplaces.html',
controller: 'ListCtrl'
}).when('/getmonth', {
templateUrl: 'templates/getmacs.html',
controller: 'MonthlyCtrl'
})
}])
Then when you create a separate controller in each file just reference the application name as such:
myApp.controller('MonthlyCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.visible = true;
}])
You will also notice I am using the array initializer way, this will save you some hastles when you are doing minification.
You can follow this convention:
First load all the library dependencies like angular, angular-routes etc
then your config holder js file which contains your module declaration.
then all other files with controller methods.
I would map specific modules to functionality (and not by layers), each one containing its concerned controllers, services and appropriate directives.
You would have one module called 'places.list' for instance, containing all controllers, services/factories and directives associated to it.
The rule is: one module, one file, otherwise you would be forced to declare those files in order... (first modules declaration..then controllers etc.. ugly)
If you split your modules in the right way, you will notice that each one is easy to maintain and doesn't contain in general a huge amount of code.
Even each route declaration (.config) would be split across those modules.
=> All the route concerning places would be declared inside the module places.list.
Indeed, it would be ugly (and difficult to maintain) to declare the whole navigation rules in your main module..
Thus, each module would be easily testable by loading only specific module's dependencies that are relevant for the test.
Related
I currently have 3 angularjs modules, each of which are (roughly) like so:
(function () {
var generalApp = angular.module('general-app', []);
generalApp.controller("NewsletterSignup.Controller", ["$scope", "$http", NewsletterSignupControllerFunction]);
}());
where NewsletterSignupControllerFunction is a global variable that is a reference to a function, eg:
var NewsletterSignupControllerFunction = function ($scope, $http) { ... };
Rather than use a global variable to share logic between the three modules, what is the simplest way to inject NewsletterSignupControllerFunction into each of the modules so I can use it to create the controllers? I have tried various approaches, none of which I can get to work.
One approach is to define a common module with the controller:
common.js
(function () {
angular.module('common', [])
.controller("NewsletterSignup.Controller",
["$scope", "$http", NewsletterSignupControllerFunction]
)
function NewsletterSignupControllerFunction ($scope,$http) {
//code ...
}
}());
Use that common module as a dependency:
angular.module("myApp",['common'])
For more information, see
AngularJS angular.module API Reference
I'm getting an error when running my app: Argument 'AppCtrl' is not a function, got undefined - I believe it has something to do with the separation of controller files?
Ok, so I have in my first file: app.js this:
angular.module('zerochili', [
'ionic',
'zerochili.controllers',
'zerochili.services',
'zerochili.directives'
])
Then I have some different controller files - Lets take the file there the AppCtrl is - This looks like the following:
angular.module('zerochili.controllers', [])
.controller('AppCtrl', ['$scope', '$ionicModal', '$timeout', function ($scope, $ionicModal, $timeout){
}])
And another file fx like so:
angular.module('zerochili.controllers', [])
.controller('LoginCtrl', ['$scope', '$state', '$ionicPopup', '$timeout', function($scope, $state, $ionicPopup, $timeout){
}]);
What am I doing wrong? Can't seem to quite figure it out?
You can think of your app.js as the part where you define the module. The controller files should be adding to the module (not have ", []" as this creates the module).
You should probably be doing this in your controllers
angular.module('zerochili')
.controller('AppCtrl', etc.
So, remove these: 'zerochili.controllers', 'zerochili.services', 'zerochili.directives' from the app.js and add your controllers,services and directives to the 'zerochili' module like above.
If you want to keep, for example, 'zerochili.controllers' make sure that you don't create this module twice, i.e. have angular.module('zerochili.controllers', []) twice.
It's only because you are creating a new modul with []
you can put at the end of your app.js
angular.module('zerochili.controllers', []);
angular.module('zerochili.directives', []);
angular.module('zerochili.services', []);
and then use it like this:
angular.module('zerochili.controllers')...
I have three different application files (in addition to vendor files) for my angular app loaded in this order
app.js
store.js
controller.js
The code from the different files is only visible to the others if I'm using a global variable, however, I thought if I used modules by starting each file like this
angular.module('myApp',
then I could avoid a global and have code defined in each file available to the others.
Example
if I do it this way with the global variable myApp then the storage provider is available in the controller.
var myApp = angular.module('myApp', ['LocalStorageModule'])
.config(['localStorageServiceProvider',
function(localStorageServiceProvider) {
localStorageServiceProvider.setPrefix('my-app');
}]);
myApp.factory('myStorage',
//code ommitted
myApp.controller('MyCtrl', [$scope, 'myStorage',
function MyController($scope, myStorage){
}
]);
However, if in the three files, I instead do it this way (without the global) then I get an unknownProvider error in myCtrl
angular.module('myApp', ['LocalStorageModule'])
.config(['localStorageServiceProvider',
function(localStorageServiceProvider) {
localStorageServiceProvider.setPrefix('my-app');
}]);
angular.module('myApp', [])
.factory('myStorage',
//code omitted
angular.module('myApp', [])
.controller('MyCtrl', [$scope, 'myStorage',
function MyController($scope, myStorage){
}
]);
Question: IN the example above, how can I make the storage from the factory available in the controller without using the global variable pattern?
You should only define module once, and use it in rest of the places. Otherwise it gets overwritten. Please remove the dependency array from module definition for factory & controller. Hope that helps.
angular.module('myApp')
.factory('myStorage',
//code omitted
angular.module('myApp')
.controller('MyCtrl', ['$scope', 'myStorage',
function ($scope, myStorage){
}
]);
Also your controller declaration is needs to be corrected as above.
The Best way to inject any service, factory etc... this way reduce Complicity...
`angular.module('myApp')
.factory('myStorage',
//code omitted
angular.module('myApp')
.controller('MyCtrl', myCtrlFun);
myCtrlFun.$inject = ['$scope', 'myStorage'];
function myCtrlFun($scope, myStorage){
}
`
In my .config I have a router that instantiate a pair controller-router:
angular.module('reporting', ['ng', 'ngRoute', 'ngResource', 'reporting.directives', 'reporting.controllers', 'reporting.config', 'ngGrid', 'ui.bootstrap'])
.config(["$routeProvider", "$provide", function ($routeProvider, $provide) {
$routeProvider
.when('/dealersReq', {
templateUrl: 'reporting/partials/dealersReqs.html',
controller: 'DealersCtrl'
})
.when('/lmtReq', {
templateUrl: 'reporting/partials/lmt.html',
controller: 'lmtCtrl'
})
.when('/leadsCreated', {
templateUrl: 'reporting/partials/leadsCreated.html',
controller: 'LeadsCreatedCtrl'
})
...
but each controller share the same initialization code (think about it like a constructor) that sets in the rootScope some variable like a title and other useful information for some controllers outside the <view>:
.controller('DealersCtrl', ['$scope','$rootScope', 'CONFIG',
function($scope, $rootScope, CONFIG) {
//////////// duplicated code
var key = 'qtsldsCrtSncheQ';
$rootScope.openReport.key = key;
$rootScope.openReport.title = CONFIG.reports['' + key].title;
//////////// duplicated code
console.log('Initialized! Now I do what a controller should really do');
}]);
What I would like to do is finding a way to move that code - which is duplicated into every controller at the moment - into something smarter and neater. Soemthing that the route can call during the routing instanciation for example. Of course each controller should have a different key, but that one could be exactly the controller name actually. I really don't know how to improve this. Any suggestion?
Why don't create a method on the $rootScope which does that, and then call it from each controller, i.e.: $rootScope.init().
You could use a Service for shared code but you should avoid to use $rootScope
https://stackoverflow.com/a/16739309/3068081
I have nested angularJS modules EventList and EventPage.
The directory structure looks like this:
app.js
EventForm
|_ EventList.js
eventListView.html
EventPage
|_EventPage.js
eventPageView.html
Eventlist.js:
angular.module('EventList', ['EventPage'])
.config([ '$routeProvider', function config($routeProvider){
$routeProvider.when(Urls.EVENT_LIST, {
templateUrl: 'app/EventList/event-list.html',
controller: 'EventListCtrl'
});
}])
.controller('EventListCtrl', ['$scope', '$location', '$http', function EventListController($scope, $location, $http) {
}]);
EventPage.js:
angular.module('EventPage', [])
.config([ '$routeProvider', function config($routeProvider){
$routeProvider.when(Urls.EVENT_PAGE + '/:id', {
templateUrl: 'app/EventList/EventPage/event-page.html',
controller: 'EventPageCtrl'
})
}])
.controller('EventPageCtrl', ['$scope', '$routeParams', '$http', function EventPageController($scope, $routeParams, $http) {
}]);
Obviously the templateUrl is hardcoded right now. My question is what is the best way to set the templateUrl in the routeProvider so the modules aren't dependent on the hard coded directory structure and can be taken out and reused in other AngularJS projects without breaking? Is there a way to just get insertViewNameHere.html in the current folder?
If you're using Grunt, this is easy. Not because modularizing AngularJS is trivial, but because all the hard work has already been done for you by the good folk doing angular-bootstrap...
When I faced this problem I simply downloaded their Gruntfile and changed every ui.bootstrap to my-angular-module. Since I mimicked their basic directory structure, it worked right out of the box.
Also, you might want to update the Angular and Bootstrap versions. E.g., change
ngversion: '1.0.8',
bsversion: '2.3.1',
to
ngversion: '1.2.3',
bsversion: '3.0.2',